开发者

SubString StringBuilder c#

开发者 https://www.devze.com 2023-02-10 11:19 出处:网络
I\'m trying : 1string pal = \"Juan1David1Correa\"; 2StringBuilder sb = new StringBuilder(pal); 3Console.writeline( sb.ToString开发者_StackOverflow(0,9) );

I'm trying :

1  string pal = "Juan     1David     1Correa";
2  StringBuilder sb = new StringBuilder(pal);
3  Console.writeline( sb.ToString开发者_StackOverflow(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?


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.


Second parameter is length, so it should be

Console.writeline( sb.ToString(10,5) );


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."


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


The second argument is length, not "end character". It cannot find 14 characters starting from 10th - hence the error.


When I run this, the exception is thrown on line 5, which makes perfect sense, as there are not enough characters in your input string to generate 26 characters starting at 15.


first of all you should document us which exception you get instead of leaving us in the dark to try to figure it out ourselves, then as a guess, I would say that your string does not contain more than 24 chars...


The StringBuilder.ToString method does not work as you expect. The parameters are:

  1. startIndex: The starting position of the substring in this instance.
  2. length: The length of the substring.

So you are starting at index 15 and trying to get the next 26 characters, which goes beyond the length of the string.

The documentation can be found here.


Please double-check that your string contains space characters within it and not tab characters. This is the only reason you can have an exception on line 4. But even if your string contains spaces you will have an exception on line 5 because 26 is the lenght of the substring, not the index of the last character.

0

精彩评论

暂无评论...
验证码 换一张
取 消