你想知道在C#中使用string.Substring()方法时,如果指定的长度超出了字符串本身的长度,是否会抛出异常,这个问题很关键,直接关系到代码的健壮性。
回答主体
在C#中,直接使用Substring方法时,如果指定的长度超出了字符串剩余可截取的长度,会抛出异常(ArgumentOutOfRangeException)。不过要注意Substring有两个重载,行为略有不同:
1. 两个参数重载:Substring(int startIndex, int length)
这个重载需要指定起始索引和截取长度,如果 startIndex + length 超过字符串总长度,就会报错。
string text = "Hello";
try
{
// 起始索引0,要截取6个字符,但字符串只有5个,会报错
string result = text.Substring(0, 6);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"报错了:{ex.Message}");
}
2. 单参数重载:Substring(int startIndex)
这个重载只指定起始索引,会截取从起始位置到字符串末尾的所有字符,即使起始索引接近字符串末尾(只要不越界),也不会报错:
string text = "Hello";
// 起始索引3,截取到末尾,结果是 "lo",不会报错
string result = text.Substring(3);
// 但如果起始索引超过字符串长度(比如5),依然会报错
try
{
string errorResult = text.Substring(5);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"报错了:{ex.Message}");
}
3. 安全截取的最佳实践
为了避免报错,建议在截取前先计算有效长度,或者使用更安全的写法:
string text = "Hello";
int startIndex = 0;
int desiredLength = 6;
// 计算实际可截取的长度(取最小值)
int actualLength = Math.Min(desiredLength, text.Length - startIndex);
// 确保起始索引不越界
if (startIndex < text.Length)
{
string safeResult = text.Substring(startIndex, actualLength);
Console.WriteLine(safeResult); // 输出 "Hello"
}
else
{
Console.WriteLine("起始索引超出范围");
}
从C# 8.0开始,还可以使用范围运算符(Range) 来更简洁地安全截取,它不会抛出异常:
string text = "Hello";
// 截取0到6的范围,自动截断到字符串末尾,结果是 "Hello"
string rangeResult = text[0..6];
Console.WriteLine(rangeResult);
总结
Substring(int startIndex, int length):长度不足时会抛出ArgumentOutOfRangeException异常;Substring(int startIndex):只要起始索引不越界,即使到字符串末尾也不会报错;- 安全写法:要么用
Math.Min计算有效长度,要么使用C# 8.0+的范围运算符[x..y]。
本文使用 文章同步助手 同步