字符串转换c#

时间:2013-12-19 05:45:02

标签: linq lambda

我想将逗号分隔的字符串格式化为字符串,没有空格,没有额外的逗号,并删除c#中的空条目。

string valueString = "sam, mike,   , ,john  , Tom and Jerry  , "

和预期结果是带有修剪值的字符串数组,如下所示

string formattedString = "sam, mike, john, Tom and Jerry"

逗号后面应该有一个空格(“,”)到格式化字符串

4 个答案:

答案 0 :(得分:2)

试试这个:

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

var nonEmpty = from s in valueString.Split(',')
    where !String.IsNullOrWhiteSpace(s)
    select s.Trim();

string formattedString = nonEmpty.Join(", ");

Console.WriteLine(formattedString);

答案 1 :(得分:2)

var sb = new StringBuilder();
foreach (string s in valueString.Split(new { "," }, StringSplitOptions.RemoveEmptyEntries))
{
    sb.Append(s.Trim());
}
string result = sb.ToString();

答案 2 :(得分:2)

试试这个

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

var strOutput= from s in valueString.Split(',')
                where !String.IsNullOrWhiteSpace(s.Trim())
                select s.Trim();

string formatString = string.Join(", ", strOutput);

Console.WriteLine(formatString);

答案 3 :(得分:0)

又一个变体,现在使用正则表达式

string valueString = "sam, mike,   , ,john  , Tom and Jerry  , ";
string formattedString = (new Regex(@"(\s*)(?<val>[^,]+)(\s*,)?").Replace(valueString,m=>{
            var res = m.Groups["val"].Value.Trim(); 
            return string.IsNullOrEmpty(res)? string.Empty : (res+", ");
        })).Trim(", ".ToCharArray());