拆分逗号分隔字符串,同时消除空白和空项 [英] Split a comma separated string while removing whitespace and empty entries

查看:1580
本文介绍了拆分逗号分隔字符串,同时消除空白和空项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个逗号分隔的字符串转换为字符串数组,并删除空白和空项。例如,给定的输入:

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

我曾尝试code这修剪值以下行,但这无法删除空的条目:

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?

推荐答案

与使用 StringSplitOptions.RemoveEmptyEntries 不起作用,因为裁剪,不考虑空项。你需要做一个正常的分裂,然后修剪各项目,然后筛选出空字符串。

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();

这篇关于拆分逗号分隔字符串,同时消除空白和空项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆