如何用两个连续的空格分割字符串

Anj*_*ali 7 c# string split space

我有一个由连续空格组成的字符串

a(double space)b c d (Double space) e f g h (double space) i
Run Code Online (Sandbox Code Playgroud)

分裂像

a
b c d
e f g h
i
Run Code Online (Sandbox Code Playgroud)

目前我正在尝试这样

   Regex r = new Regex(" +");
        string[] splitString = r.Split(strt);
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 15

你可以使用String.Split:

var items = theString.Split(new[] {"  "}, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)


Mik*_*sen 5

string s = "a  b c d  e f g h  i";
var test = s.Split(new String[] { "  " }, StringSplitOptions.RemoveEmptyEntries);

Console.WriteLine(test[0]); // a
Console.WriteLine(test[1]); // b c d
Console.WriteLine(test[2]); // e f g h
Console.WriteLine(test[3]); // i
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用正则表达式,它使您可以在任何空格上分割两个字符:

string s = "a      b c d   e f g h      \t\t i";
var test = Regex.Split(s, @"\s{2,}");

Console.WriteLine(test[0]); // a
Console.WriteLine(test[1]); // b c d
Console.WriteLine(test[2]); // e f g h
Console.WriteLine(test[3]); // i
Run Code Online (Sandbox Code Playgroud)