You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C#中长度为1的字符串调用Substring(1)返回空字符串而非异常?

C# String.Substring(startIndex) 返回空字符串的原因解析

问题场景

执行以下代码:

char a1='a';
string s1=char.ToString(a1);
string s2 = s1.Substring(1);

代码执行后,s2的值为string.Empty(即"")。按常规理解,s1仅包含1个字符,索引1超出范围,s1.Substring(1)应该抛出IndexOutOfRangeException,但实际结果与预期不符。

在即时窗口中的测试结果如下:

s1
"a"
s1[0]
97 'a'
s1[1]
's1[1]' threw an exception of type 'System.IndexOutOfRangeException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233080
    HelpLink: null
    InnerException: null
    Message: "Index was outside the bounds of the array."
    Source: "System.Private.CoreLib"
    StackTrace: "   at System.ThrowHelper.ThrowIndexOutOfRangeException()\r\n   at System.String.get_Chars(Int32 index)"
    TargetSite: {Void ThrowIndexOutOfRangeException()}
s1.Substring(0)
"a"
s1.Substring(1)
""

另外,s1.Substring(2)能正确抛出ArgumentOutOfRangeException,但Substring(1)返回空字符串的现象令人费解。

原因解析

这是String.Substring(int startIndex)方法的既定行为,并非异常或版本问题。该方法的核心逻辑为:

从此实例中返回从startIndex位置开始的子字符串;若startIndex等于实例的长度,则返回Empty字符串。

需要注意直接索引访问与Substring方法的差异:

  • 直接通过s1[index]访问字符时,索引必须严格小于字符串长度,否则抛出IndexOutOfRangeException;
  • Substring方法允许startIndex等于字符串长度,此时相当于从字符串末尾的下一个位置开始截取,没有可返回的字符,因此返回空字符串;只有当startIndex大于字符串长度时,才会抛出ArgumentOutOfRangeException。

内容的提问来源于stack exchange,提问作者Vikram Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:05:18