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?

2

3 Answers 3

12

Just remove empty strings from result:

var allId = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Sign up to request clarification or add additional context in comments.

4 Comments

Beat me to it, You should always look and see if there are more overrides than the basic function signature.
@SheridanBulger +1, overloads often help
@hometoast, btw I think you need to create array of chars, when you use overload with split options
I always screw up my inline-array declarations. So I stick with " ".ToCharArray(). #lazy (and yes your'e right, I got the signature wrong. StringSplitOptions requires and array as first argument -- good catch.)
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.