Mack
Mack

Reputation: 179

Treat Many Whitespace Characters As a Single Delimiter

When the method String.Split(null) encounters many whitespace characters in a row it treats each whitespace character as a delimiter.

So for the following string a b c d the result is:

{"a", "b", "c", , , "d"}   // for string[] res = "a b c   d".Split(null);

Is it possible to to make String.Split(null) treat many whitespace characters as a single delimiter? Is there a different method that can do this?

Ie, is there a method that will achieve this result:

{"a", "b", "c", "d"}

Before I go and reinvent the wheel (write my own method to convert multiple whitespace characters to a single char then use String.Split(null)) I want to check that there isn't an existing method that will do this for me.

Upvotes: 0

Views: 54

Answers (2)

porges
porges

Reputation: 30590

You need to pass StringSplitOptions.RemoveEmptyEntries. This will remove the extra entries in the list. To keep the default (i.e. whitespace) splitting you can continue to pass null as the first argument, e.g:

"a b c   d".Split((char[])null, StringSplitOptions.RemoveEmptyEntries)

Upvotes: 0

David Pilkington
David Pilkington

Reputation: 13618

You need to add this StringSplitOptions.RemoveEmptyEntries to the Split method. There is an overload that takes in this enum

yourString.Split(null, StringSplitOptions.RemoveEmptyEntries)

Upvotes: 2

Related Questions