2013-10-02 63 views
5

我有一个由连续的空间像如何将一个字符串以两个连续的空格

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); 
将字符串分割
+0

您是否尝试过拆分(“”)? –

+0

@bobek这是行不通的 – Servy

+0

.Split(“Doublespace”)? – sgud

回答

13

您可以使用String.Split

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

谢谢它适用于我 – Anjali

3

您可以使用String.Split方法。

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

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

1

使用正则表达式是一个完美的解决方案

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

这是如何拆分字符串? –

+0

阅读这些:http://www.dotnetperls.com/regex-match –

+0

我知道'Regex.Match'如何工作。我不认为它实现了OP的要求。 '-1'。 –

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

相关问题