Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string variable on a space or 2 spaces in C#

Tags:

string

c#

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?

like image 388
karan k Avatar asked Oct 16 '12 16:10

karan k


1 Answers

Just remove empty strings from result:

var allId = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
like image 193
Sergey Berezovskiy Avatar answered Oct 30 '22 10:10

Sergey Berezovskiy