我有一个文本字符串,当它超过特定长度时,我将字符串分成 2 个字符串,将剩余内容的其余部分传递给另一个变量,但我有一个例外
索引和长度必须引用字符串中的位置。(参数“长度”)
我的 C# 代码:
string text = "Hello word jeje";
if (text.Length > 10)
{
string stringOne = text.Substring(0, 10);
string stringTwo = text.Substring(11, text.Length); //throw exception
}
Run Code Online (Sandbox Code Playgroud)
预期结果:
string text = "Hello word jeje";
string stringOne = "Hello";
string stringTwo = " jeje";
Run Code Online (Sandbox Code Playgroud)
你有一个相差一的错误;你需要text.Length - 1。
接受和参数的双参数版本String.Substring();你需要。startlengthtext.Substring(11, text.Length - 11)
但是,您可以在后半部分保留第二个参数,因为String.Substring() 的单参数版本将子字符串返回到字符串的末尾。
string stringOne = text.Substring(0, 10);
string stringTwo = text.Substring(11);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2009 次 |
| 最近记录: |