Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a comma separated string while removing whitespace and empty entries

I wanted to convert a comma-separated string to a string-array and also remove whitespace and empty entries. For example, given the input:

string valueString = "sam, mike,   , ,john  , Tom and jerry  , "; 

The expected result would be the following values (trimmed, of course):

sam mike john Tom and Jerry 

I have tried the following line of code which trims the values, but this fails to remove "empty" entries:

valueString.Split(',').Select(sValue => sValue.Trim()).ToArray(); 

What would be the best way to go about trimming the input and cleaning up and empty entries that might result in the process?

like image 220
Sameer Avatar asked Dec 18 '13 15:12

Sameer


People also ask

How do you split a string and delete spaces?

To split a string and trim the surrounding spaces: Call the split() method on the string. Call the map() method to iterate over the array. On each iteration, call the trim() method on the string to remove the surrounding spaces.

How do you split a comma separated string?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you separate comma separated values into a list?

Split the String into an array of Strings using the split() method. Now, convert the obtained String array to list using the asList() method of the Arrays class.


1 Answers

Using Trim with StringSplitOptions.RemoveEmptyEntries doesn't work because " " isn't considered an empty entry. You need to do a normal split, then trim each item, then filter out the empty strings.

valueString.Split(',')     .Select(x => x.Trim())     .Where(x => !string.IsNullOrWhiteSpace(x))     .ToArray(); 
like image 145
Anthony Avatar answered Oct 09 '22 02:10

Anthony