令人惊讶的子串的行为 [英] Surprising Substring behavior

查看:138
本文介绍了令人惊讶的子串的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到这种行为来今天在使用子字符串方法:

I came across this behavior today while using the Substring method:

static void Main(string[] args) {
    string test = "123";
    for (int i = 0; true; i++) {
        try {
            Console.WriteLine("\"{0}\".Substring({1}) is \"{2}\"", test, i, test.Substring(i));
        } catch (ArgumentOutOfRangeException e) {
            Console.WriteLine("\"{0}\".Substring({1}) threw an exception.", test, i);
                break;
        }
    }
}



输出:

Output:

"123".Substring(0) is "123"
"123".Substring(1) is "23"
"123".Substring(2) is "3"
"123".Substring(3) is ""
"123".Substring(4) threw an exception.



123.Substring(3)返回一个空字符串和123.Substring(4)抛出一个异常。然而,123[3]和123[4]都是出界。这是记录在MSDN上 ,但我有一个很难理解为什么子字符串的方法是这样的写法。我期望的任何超出界限指标要么总是导致异常或总是导致一个空字符串。任何见解?

"123".Substring(3) returns an empty string and "123".Substring(4) throws an exception. However, "123"[3] and "123"[4] are both out of bounds. This is documented on MSDN, but I'm having a hard time understanding why the Substring method is written this way. I'd expect any out-of-bounds index to either always result in an exception or always result in an empty string. Any insight?

推荐答案

内部实现 String.Substring的(的startIndex)是这样的。

public string Substring(int startIndex)
{
    return this.Substring(startIndex, this.Length - startIndex);
}



所以,你所要求的零个字符长度的字符串。 (又名的String.Empty)
我同意你,这是不是对MS的部分清晰,但没有更好的解释,我认为这是更好地给这个结果不是抛出异常。

So you are asking for a string of zero characters length. (A.K.A. String.Empty) I concur with you that this is not clear on MS part, but without a better explanation I think that is better to give this result than throwing an exception.

String.Substring(的startIndex,长度)我们看到这个代码

if (length == 0)
{
    return Empty;
}



所以,因为长度= 0是在第二过载的有效输入,我们得到的结果也为第一个。

So, because length=0 is a valid input in the second overload, we get that result also for the first one.

这篇关于令人惊讶的子串的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆