C#中子字符串的异常行为 [英] Unexpected behavior of Substring in C#
问题描述
.net System.String
类中 Substring()
方法的定义就像这样
The definition of Substring()
method in .net System.String
class is like this
public string Substring(int startIndex)
其中 startIndex
是根据该方法定义,此实例中子字符串的从零开始的字符位置 。如果我正确理解它,则意味着它将给我一部分字符串,从给定的从零开始的索引开始。
Where startIndex
is "The zero-based starting character position of a substring in this instance" as per the method definition. If i understand it correctly, it means it will give me a part of the string, starting at the given zero-based index.
现在,如果我有一个字符串 ABC
并使用具有不同索引的子字符串,我得到以下结果。
Now, if I have a string "ABC"
and take substring with different indexes, I get following results.
var str = "ABC";
var chars = str.ToArray(); //returns 3 char 'A', 'B', 'C' as expected
var sub2 = str.Substring(2); //[1] returns "C" as expected
var sub3 = str.Substring(3); //[2] returns "" ...!!! Why no exception??
var sub4 = str.Substring(4); //[3] throws ArgumentOutOfRangeException as expected
为什么不为案例[2]抛出异常??
Why it doesn't throw exception for case [2] ??
该字符串具有3个字符,因此索引为 [0,1,2]
甚至 ToArray()
, ToCharArray()
方法将按预期返回3个字符!如果我尝试使用起始索引为 3
的 Substring()
抛出异常?
The string has 3 characters, so indexes are [0, 1, 2]
, and even ToArray()
, ToCharArray()
method returns 3 characters as expected! Shouldn't it throw exception if I try to Substring()
with starting index 3
?
推荐答案
文档非常明确地表明这是正确的行为:
The documentation is quite explicit about this being correct behaviour:
返回值:一个等效于字符串的字符串在这种情况下以startIndex开头的子字符串;如果startIndex等于该实例的长度,则为 Empty。
Return value: a string that is equivalent to the substring that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance.
如果 startIndex
小于零或 *大于此实例的长度,则引发 ArgumentOutOfRangeException
。 *
Throws ArgumentOutOfRangeException
if startIndex
is less than zero or *greater than the length of this instance. *
换句话说,从子字符串开始直到最后一个字符都将为您提供一个空字符串。
In other words, taking a substring starting just beyond the final character will give you an empty string.
您希望它给您字符串的部分的注释与此不兼容。 字符串的一部分还包括所有长度为零的所有子字符串的集合,这由 s.substring(n,0)
将也给出一个空字符串。
Your comment that you expected it to give you a part of the string is not incompatible with this. A "part of the string" includes the set of all substrings of zero length as well, as evidenced by the fact that s.substring(n, 0)
will also give an empty string.
这篇关于C#中子字符串的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!