【问题标题】:Remove extra commas in C#在 C# 中删除多余的逗号
【发布时间】:2010-12-11 19:17:22
【问题描述】:

我有一个类似“abc,,bcd”的字符串;

输出应该是 abc,bcd 即多余的逗号应该被删除。

需要帮助

【问题讨论】:

  • 字符串是否包含像“, ," 之类的子字符串?

标签: c#-3.0


【解决方案1】:
string result = Regex.Replace(input, ",+", ",").Trim(',');

【讨论】:

  • 很好,想告诉你你错过了尾随的 Trim(',')。但我看到你后来修好了。
【解决方案2】:
string input = "abc,,bcd,";
string output = String.Join(",",
    input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
);

【讨论】:

    【解决方案3】:

    怎么样

    string s = "abc,,bcd,";
    s = s.Trim(',');
    while (s.Contains(",,"))
        s = s.Replace(",,", ",");
    

    【讨论】:

    【解决方案4】:

    您可以尝试将字符串拆分为数组。 然后循环遍历数组。 检查当前元素是否具有您认为可以接受的值。 将该值附加到字符串生成器。 如果这不是数组的最后一个元素,则在字符串生成器中附加一个逗号。

    【讨论】:

      【解决方案5】:
      string input = "abc,,bcd,";
      
      input.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Aggregate((a, b) => a + "," + b);
      

      【讨论】:

      • 只需使用string.Join 而不是Aggregate。它更易读,速度更快(一次连接)。
      猜你喜欢
      • 2013-12-10
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2019-08-29
      • 1970-01-01
      • 2017-10-04
      相关资源
      最近更新 更多