Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SubString StringBuilder c#

I'm trying :

1  string pal = "Juan     1David     1Correa";
2  StringBuilder sb = new StringBuilder(pal);
3  Console.writeline( sb.ToString(0,9) );
4  Console.writeline( sb.ToString(10,14) );
5  Console.writeline( sb.ToString(15,26) );

But in the 4 line It throws an exception.

Why?

like image 646
Daniel Gomez Rico Avatar asked Feb 15 '11 17:02

Daniel Gomez Rico


4 Answers

The second argument to StringBuilder.ToString(int, int) represents the length of the desired sub-string, not its end-index.

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

For example, the last statement should probably be:

Console.WriteLine(sb.ToString(15, 12));

On another note, If all you want is to get sub-strings from the original string, you could just use the String.Substring(int, int) method.

like image 96
Ani Avatar answered Nov 16 '22 11:11

Ani


Second parameter is length, so it should be

Console.writeline( sb.ToString(10,5) );
like image 42
Tokk Avatar answered Nov 16 '22 11:11

Tokk


The docs clearly state that ArgumentOutOfRangeException will be thrown when "The sum of startIndex and length is greater than the length of the current instance."

like image 20
Mark Rushakoff Avatar answered Nov 16 '22 11:11

Mark Rushakoff


Second parameter is length but not a last index. So in your case 15+26 = 41 which is out of the bounds.

like image 31
Oleg Rudckivsky Avatar answered Nov 16 '22 11:11

Oleg Rudckivsky