简体   繁体   English

拆分逗号分隔的字符串,同时删除空格和空条目

[英]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?修剪输入和清理可能导致该过程的空条目的最佳方法是什么?

Using Trim with StringSplitOptions.RemoveEmptyEntries doesn't work because " " isn't considered an empty entry.将 Trim 与StringSplitOptions.RemoveEmptyEntries一起使用不起作用,因为" "不被视为空条目。 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();

Building on the answer from Anthony, this will convert it back to a comma delimited string as well:基于 Anthony 的答案,这也会将其转换回逗号分隔的字符串:

valueString = string.Join(",", valueString.Split(',')
    .Select(x => x.Trim())
    .Where(x => !string.IsNullOrWhiteSpace(x))
    .ToArray())

试试这个,它适用于我的......

item.Split({"|"}, StringSplitOptions.RemoveEmptyEntries)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM