Created
December 13, 2012 20:00
-
-
Save noblethrasher/4279302 to your computer and use it in GitHub Desktop.
A lazier StringBuilder...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed class StringBuilderEx | |
{ | |
readonly List<Func<string>> parts; | |
Func<string, string> replace = null; | |
public int Capacity | |
{ | |
get | |
{ | |
return parts.Capacity; | |
} | |
} | |
public StringBuilderEx(int n) | |
{ | |
parts = new List<Func<string>> (n); | |
} | |
public StringBuilderEx() | |
{ | |
parts = new List<Func<string>> (); | |
} | |
public void Append(string s) | |
{ | |
parts.Add (() => s); | |
} | |
public void AppendLine(string s) | |
{ | |
parts.Add (() => s + Environment.NewLine); | |
} | |
public void AppendFormat(string format, params object[] objs) | |
{ | |
parts.Add (() => string.Format (format, objs)); | |
} | |
public void AppendFormat(Func<string> format, params object[] objs) | |
{ | |
parts.Add (() => string.Format (format(), objs)); | |
} | |
public void AppendFormat(Func<string> format, params Func<object>[] objs) | |
{ | |
Func<string> thunk = () => | |
{ | |
var evaluated_objs = new object[objs.Length]; | |
for (var i = 0; i < objs.Length; i++) | |
evaluated_objs[i] = objs[i] (); | |
return string.Format (format (), evaluated_objs); | |
}; | |
parts.Add (thunk); | |
} | |
public void Append(Func<string> f) | |
{ | |
parts.Add (f); | |
} | |
public void AppendLine(Func<string> f) | |
{ | |
parts.Add (() => f () + Environment.NewLine); | |
} | |
public void InsertAt(int n, Func<string> f) | |
{ | |
parts.Insert (n, f); | |
} | |
public void Clear() | |
{ | |
parts.Clear (); | |
} | |
public StringBuilderEx Replace(char oldChar, char newChar) | |
{ | |
replace = s => s.Replace (oldChar, newChar); | |
return this; | |
} | |
public StringBuilderEx Replace(string oldString, string newString) | |
{ | |
replace = s => s.Replace (oldString, newString); | |
return this; | |
} | |
public void RemoveAt(int n) | |
{ | |
parts.RemoveAt (n); | |
} | |
public override string ToString() | |
{ | |
var temp_array = new string[parts.Count]; | |
if (replace != null) | |
for (var i = 0; i < parts.Count; i++) | |
temp_array[i] = replace (parts[i] ()); | |
else | |
for (var i = 0; i < parts.Count; i++) | |
temp_array[i] = parts[i] (); | |
return string.Join ("", temp_array); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment