【问题标题】:String Join How to Ignore Both Empty and LineBreaks字符串连接如何忽略空和换行符
【发布时间】:2017-12-30 08:30:25
【问题描述】:

这是示例代码。

我可以连接所有字符串并用空格分隔它们。

如果字符串是Empty,连接将被忽略,防止出现双空格。

如何在相同的ColorList.Where() 参数中也忽略换行符\n

string red = "Red";
string blue = "Blue";
string yellow = "\n\n";
string green = string.Empty;

List<string> ColorList = new List<string>()
{
    red,
    blue,
    yellow,
    green
};

string colors = string.Join(" ", ColorList.Where(s => !string.IsNullOrEmpty(s)));

【问题讨论】:

    标签: c# string removing-whitespace


    【解决方案1】:

    只需将.Where(s =&gt; !s.Contains("\n")) 添加到您的查询中:

    string red = "Red";
    string blue = "Blue";
    string yellow = "\n\n";
    string green = string.Empty;
    
     List<string> ColorList = new List<string>()
    {
        red,
        blue,
        yellow,
        green
    };
    
    string colors = string.Join(" ", ColorList.Where(s => !string.IsNullOrEmpty(s)).Where(s => !s.Contains("\n")));
    

    【讨论】:

    • 我会把string green = string.Empty;改成string green = null;
    • 然后将其他Where 添加为.Where(s =&gt; s != null) 以查询句柄
    • 它有效,谢谢。我用!s.Equals("\n\n")。因此,如果它是没有任何其他文本的独立 LineBreak。
    • 这也将排除red\n
    • 是的,如果你想完全删除 \n\n 然后使用 .Where(s =&gt; !s.Contains("\n\n"))
    【解决方案2】:

    你也可以使用String.IsNullOrWhiteSpace Method (String)

    指示指定的字符串是 null、空还是仅由空白字符组成。

    并为其余部分修剪任何空白。

    string red = "Red";
    string blue = "Blue";
    string yellow = "\n\n";
    string green = string.Empty;
    string black = null;
    
    var ColorList = new List<string>()
    {
        red,
        blue,
        yellow,
        green,
        black
    };
    
    //Red Blue
    string colors = string.Join(" ", 
        ColorList.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim())
    );
    

    这将安全地忽略或为空、为空或只有空格的项目。它还将删除剩余项目上的任何杂散空白。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多