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

时间:2013-10-02 19:17:22

标签: c# string split space

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

a(double space)b c d (Double space) e f g h (double space) i

一样分裂
a
b c d
e f g h
i

目前我正在尝试这样

   Regex r = new Regex(" +");
        string[] splitString = r.Split(strt);

4 个答案:

答案 0 :(得分:15)

您可以使用String.Split

var items = theString.Split(new[] {"  "}, StringSplitOptions.None);

答案 1 :(得分:3)

您可以使用String.Split方法。

  

返回包含此字符串中子字符串的字符串数组   由指定字符串数组的元素分隔。一个   参数指定是否返回空数组元素。

string s = "a  b c d  e f g h  i";
var array = s.Split(new string[] {"  "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var element in array)
{
    Console.WriteLine (element);
}

输出将是;

a
b c d
e f g h
i

这里有 DEMO

答案 2 :(得分:3)

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

Example

另一种方法是使用正则表达式,它允许您在任何空白上拆分两个字符:

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

Example

答案 3 :(得分:1)

使用正则表达式是一种优雅的解决方案

string[] match = Regex.Split("a  b c d  e f g h  i", @"/\s{2,}/",  RegexOptions.IgnoreCase);