Pittfall
Pittfall

Reputation: 2851

Is there a way to do a string.Split on whitespace

I have a string "mystring theEnd" but I want to do a string.Split on white space, not just on a space because I want to get a string[] that contains "mystring" and "theEnd" between "mystring" and "theEnd" there is an unknown amount of spaces, this is why I need to split on whitespace. Is there a way to do this?

Upvotes: 0

Views: 183

Answers (2)

d--b
d--b

Reputation: 5779

Simplest is to do:

a.Split(new [] {' ', '\t'},StringSplitOptions.RemoveEmptyEntries)

Thanks Jon :)

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500225

How about:

string[] bits = text.Split(new[] {' '}, StringSplitOptions.RemoveEmptEntries);

(Or text.Split specifying the exact whitespace characters you want to split on, or using null as Henk suggested.)

Or you could use a regex to handle all whitespace characters:

Regex regex = new Regex(@"\s+");
string[] bits = regex.Split(text);

Upvotes: 7

Related Questions