如何使用C#将字符串拆分一次

9 c#

示例:a - b - c必须拆分为a和b - c,而不是3个子串

Guf*_*ffa 21

指定所需的最大项目数:

string[] splitted = text.Split(new string[]{" - "}, 2, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)

  • 我个人会为数组变量名称添加"splat"...如果你要写一个单词,我会说有兴趣! (4认同)

Agi*_*Jon 13

string s = "a - b - c";
string[] parts = s.Split(new char[] { '-' }, 2);
// note, you'll still need to trim off any whitespace
Run Code Online (Sandbox Code Playgroud)


tan*_*ius 5

"a-b-c".Split( new char[] { '-' }, 2 );
Run Code Online (Sandbox Code Playgroud)