5

I have a string variable, which is basically 3 strings, separated by one space each.These 3 strings may vary in length. Like

string line="XXX YY ZZ";

Now, it occassionally happens that my string variable line, consists of 3 strings, where the first and the second string are separated by 2 spaces, instead of one.

string line="XX  YY ZZ";

What I wanted to do is store the 3 strings in a string array.Like:

string[] x where x[0]="XXX" , x[1]="YY" , x[2]="ZZ"

I tried to use the Split function.

string[] allId = line.Split(' ');

It works for the first case, not for the second. Is there any neat, simple way to do this?

karan k
  • 947
  • 2
  • 21
  • 45

3 Answers3

12

Just remove empty strings from result:

var allId = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
8

Use Regex split. Why? Space is not the only character representing a space; there are tabs as well.

By using regex split with a \s+ pattern, that operation will consume all space combinations even with a mixture of tabs and spaces, thus allowing text to be returned. Example

var result = Regex.Split("XX  YYY    ZZZ", @"\s+");

// "XX", "YYY", "ZZZ" returned in array

Linqpad results image capture

Pattern Summary

\s means any non character, a space or tab. + after it says, I expect at least one, but more than one can be found.

So the + after the \s means that the regex processor will look for one or more spaces to split on as a match. Everything between the matches will be returned.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
2

You use the split method with an extra parameter.

The .split method is documented here.

The 2nd parameter options is of type StringSplitOptions and is defined here.

The 2 possible values of this parameter are StringSplitOptions.None and StringSplitOptions.RemoveEmptyEntries.

So, simply do:

string[] allId = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);

and you have want you want! Easy.

Sethi
  • 1,378
  • 8
  • 14