Split a comma separated string while removing whit

2019-02-03 04:10发布

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?

2条回答
一夜七次
2楼-- · 2019-02-03 04:54

Building on the answer from Anthony, this will convert it back to a comma delimited string as well:

valueString = string.Join(",", valueString.Split(',')
    .Select(x => x.Trim())
    .Where(x => !string.IsNullOrWhiteSpace(x))
    .ToArray())
查看更多
混吃等死
3楼-- · 2019-02-03 05:07

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();
查看更多
登录 后发表回答