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?
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!"
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.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With