Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String.Substring equivalent for StringBuilder?

StringBuilder does not appear to have a Substring(start, len) method... what am I missing here?

like image 665
James Avatar asked Aug 12 '14 22:08

James


2 Answers

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
like image 77
Steve Avatar answered Nov 14 '22 00:11

Steve


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];
}
like image 1
terrybozzio Avatar answered Nov 14 '22 00:11

terrybozzio