如何按位置分割字符串#

Alo*_*ras 0 c# indexing split

我有一个文本字符串,当它超过特定长度时,我将字符串分成 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)

AKX*_*AKX 5

你有一个相差一的错误;你需要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)