Anjali
Anjali

Reputation: 1718

How to split a string with two continuous spaces

I have a string that consists of continuous spaces like

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

split like

a
b c d
e f g h
i

at present i am trying like this

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

Upvotes: 7

Views: 14878

Answers (4)

Harold Sota
Harold Sota

Reputation: 7566

Use regular expression is an elegant solution

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

Upvotes: 1

Mike Christensen
Mike Christensen

Reputation: 91716

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

Another way would be to use Regular Expressions, which would allow you to split on any whitespace over two characters:

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

Upvotes: 6

Soner Gönül
Soner Gönül

Reputation: 98868

You can use String.Split method.

Returns a string array that contains the substrings in this string that are delimited by elements of a specified string array. A parameter specifies whether to return empty array elements.

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);
}

Output will be;

a
b c d
e f g h
i

Here a DEMO.

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564851

You can use String.Split:

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

Upvotes: 19

Related Questions