Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the cleanest way to remove all extra spaces from a user input comma delimited string into an array

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?

like image 953
leora Avatar asked Sep 27 '09 14:09

leora


People also ask

How do I cut all spaces in C#?

Strip whitespace from the start and end of a C# string An easy way to do that is by calling C#'s Trim() method on the string: string example = " Hi there! "; string trimmed = example. Trim(); // Result: "Hi there!"

How do you store comma separated values in an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you create an array with comma separated strings?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


1 Answers

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".

like image 141
Bart Kiers Avatar answered Sep 18 '22 17:09

Bart Kiers