子字符串 StringBuilder C#
我正在尝试:
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) );
但在第 4 行中它引发了异常。
为什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
StringBuilder.ToString(int, int)< 的第二个参数/code>
表示所需子字符串的长度,而不是其结束索引。
例如,最后一个语句可能应该是:
另一方面,如果您只想从原始字符串中获取子字符串,则可以使用
String.Substring(int, int)
方法。The second argument to
StringBuilder.ToString(int, int)
represents the length of the desired sub-string, not its end-index.For example, the last statement should probably be:
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
文档明确指出
ArgumentOutOfRangeException
将是当“startIndex 和 length 之和大于当前实例的长度”时抛出。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."第二个参数是长度但不是最后一个索引。所以在你的情况下 15+26 = 41 这是超出范围的。
Second parameter is length but not a last index. So in your case 15+26 = 41 which is out of the bounds.
第二个参数是长度,而不是“结束字符”。它无法找到从第 10 个字符开始的 14 个字符 - 因此会出现错误。
The second argument is length, not "end character". It cannot find 14 characters starting from 10th - hence the error.
当我运行这个程序时,异常在第 5 行抛出,这是完全合理的,因为输入字符串中没有足够的字符来生成从 15 开始的 26 个字符。
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.
首先,您应该向我们记录您遇到的异常,而不是让我们在黑暗中尝试自己找出答案,然后作为猜测,我会说您的字符串不包含超过 24 个字符...
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...
StringBuilder.ToString
方法无法按您的预期工作。参数为:因此,您从索引 15 开始并尝试获取接下来的 26 个字符,这超出了字符串的长度。
可以在此处找到该文档。
The
StringBuilder.ToString
method does not work as you expect. The parameters are: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.
请仔细检查您的字符串中是否包含空格字符,而不是制表符。这是4 行出现异常的唯一原因。但即使您的字符串包含空格,也会在第 5 行出现异常,因为 26 是子字符串的长度,而不是最后一个字符的索引。
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.