views:

163

answers:

2

Suppose you have output like this:

Word1           Word2   Word3      Word4

Where the number of spaces between words is arbitrary. I want to break it into an array of words.

I used the following code:

string[] tokens =
         new List<String>(input.Split(' '))
             .FindAll
             (
                 delegate(string token)
                 {
                      return token != String.Empty;
                 }
             ).ToArray();

Not exactly efficient, but does the job nicely.

How would you do it?

+1  A: 

I would use a regex for the split with "\w+" for the pattern.

EBGreen
Then I'd have two problems.
FlySwat
:) - So twice as many chances to expand your abilities.
EBGreen
Actually I had the pattern wrong anyway...D'OH!
EBGreen
See, that's why I'm afraid of regex.
FlySwat
+18  A: 

He already mentions string.Split(). What he's missing is StringSplitOptions.RemoveEmptyEntries:

string[] tokens = input.Split(new char[] { ' ' },
    StringSplitOptions.RemoveEmptyEntries);
Joel Coehoorn
Genius. I didn't notice that overload.
FlySwat
+1 for using what is already there.
EBGreen
You have to admit, anonymous delegates make it look cooler =)
FlySwat
Cooler, yes, more legible and obvious ... not so much. I never noticed this overload either, but it absolutely rocks! +1!
John Rudy
The best part is that it's easy to include tabs, newlines, and other whitespace in the array if you want.
Joel Coehoorn
Wow, in all my time using things I've never noticed this overload...
Mitchel Sellers