views:

337

answers:

7

A program has users typing in a comma-delimited string into an array:

basketball, baseball, soccer ,tennis

There may be spaces between the commas or maybe not.

If this string was simply split() on the comma, then some of the items in the array may have spaces before or after them.

What is the best way of cleaning this up?

A: 

String.Replace(" ","") before you split the string

SwDevMan81
That's not good if a value contains spaces...
Guffa
OP question didnt have spaces, but you are right, this wont work for values with spaces (see David Andres answer for a better Replace)
SwDevMan81
+1  A: 

Split the items on the comma:

string[] splitInput = yourInput.Split(',', StringSplitOption.RemoveEmptyEntries);

and then use

foreach (string yourString in splitInput)
{
    yourString.Trim();
}
ChrisF
+3  A: 

You can split on either comma or space, and remove the empty entries (those between a comma and a space):

string[] values = delimitedString.Split(new char[]{',',' '}, StringSplitOption.RemoveEmptyEntries);

Edit:
However, as that doesn't work with values that contain spaces, instead you can split on the possible variations if your values can contain spaces:

string[] values = delimitedString.Split(new string[]{" , ", " ,", ", ", ","}, StringSplitOptions.None);
Guffa
As others pointed out with my answer, this will have problems with spaced values "american football, table tennis"
SwDevMan81
@SwDevMan: Yes, you are right. A added a variation that handles values containing spaces.
Guffa
regarding your second solution: it won't be possible to list all possible combinations of spaces and commas (e.g. 3 spaces, one comma, 2 spaces, ...)
M4N
+3  A: 
string s = "ping pong, table tennis, water polo";
string[] myArray = s.Split(',');
for (int i = 0; i < myArray.Length; i++)
    myArray[i] = myArray[i].Trim();

That will preserve the spaces in the entries.

RedFilter
+10  A: 

You can use Regex.Split for this:

string[] tokens = Regex.Split("basketball, baseball, soccer ,tennis", @"\s*,\s*");

The regex \s*,\s* can be read as: "match zero or more white space characters, followed by a comma followed by zero or more white space characters".

Bart Kiers
A: 

I would firstly split a text by ",", and then use Trim method to remove spaces on start and end of the each string. This will add support for string with spaces to your code.

Kamarey
+3  A: 
string[] values = delimitedString.Split(',').Select(s => s.Trim()).ToArray();
adrianbanks