次のような連続したスペースで構成される文字列があります
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);
使用できますString.Split
:
var items = theString.Split(new[] {" "}, StringSplitOptions.None);
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
もう 1 つの方法は、正規表現を使用することです。これにより、空白を 2 文字に分割できます。
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
メソッドを使用できます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
.
正規表現の使用はエレガントなソリューションです
string[] match = Regex.Split("a b c d e f g h i", @"/\s{2,}/", RegexOptions.IgnoreCase);