StringBuilder does not appear to have a Substring(start, len) method... what am I missing here?
Asked
Active
Viewed 2.4k times
3 Answers
79
The StringBuilder class has a special version of the ToString method that takes two arguments, exactly as Substring(startIndex, length).
StringBuilder sb = new StringBuilder("This is a Test");
string test = sb.ToString(10, 4);
Console.WriteLine(test); // result = Test

Steve
- 213,761
- 22
- 232
- 286
-
you can also access the Length property of the StringBuilder if you were doing something like removing the last character from the string where you would normally use `.Substring(0, sb.ToString().Length -1` – jspinella Oct 21 '20 at 21:55
-
Better doing it on the StringBuilder itself without converting it to a string and then recreating another string with one character less. _sb.Length--;_ – Steve Oct 21 '20 at 22:01
-
1mmm fair enough, a better example would be passing in non-zero for the start index where you want to filter out the first *and* last character. To be clear, my example above is what NOT to do. – jspinella Oct 21 '20 at 22:06
1
these are all ways you can get the desired substring:
StringBuilder b = new StringBuilder();
b.Append("some text to test out!");
string s = b.ToString(0, 6);
//or ....
char[] letters = new char[6];
b.CopyTo(0, letters, 0, 6);
string s1 = new string(letters);
//or
string s2 = null;
for (int i = 0; i < 6; i++)
{
s2 += b[i];
}

terrybozzio
- 4,424
- 1
- 19
- 25
-
2
-
1lol yes it is,i just wanted to present all the options available:) – terrybozzio Aug 12 '14 at 22:47
0
Another approach, if you dont want to build whole string (StringBuilder.ToString()) and get the substring:
public static StringBuilder SubString(this StringBuilder input, int index, int length)
{
StringBuilder subString = new StringBuilder();
if (index + length - 1 >= input.Length || index < 0)
{
throw new ArgumentOutOfRangeException("Index out of range!");
}
int endIndex = index + length;
for (int i = index; i < endIndex; i++)
{
subString.Append(input[i]);
}
return subString;
}

Naresh
- 374
- 1
- 4
-
1Interesting view of the question. Perhaps you could remove the loop and use simply `return new StringBuilder(input.ToString(index, length));` – Steve Aug 12 '14 at 22:41
-
@Steve - Yeah you are right, I didn't notice that stringBuilder.ToString takes arguments index and length. – Naresh Aug 12 '14 at 23:02