How can I join an array of strings but first remove the elements of the array that are empty?

后端 未结 4 2087
孤独总比滥情好
孤独总比滥情好 2021-01-17 10:56

I am using the following:

return string.Join(\"\\n\", parts);

Parts has 7 entries but two of them are the empty string \"\". How can I fi

相关标签:
4条回答
  • 2021-01-17 11:45

    Try it using LINQ

    string[] hello = new string[] { "ads", "zxc", "wer", "", "wer", "", "243" };
    string newString = string.Join("\n", hello.Where(x => x.Trim().Length != 0));
    MessageBox.Show(newString);
    

    or

    return string.Join("\n", hello.Where(x => x.Trim().Length != 0));
    
    0 讨论(0)
  • 2021-01-17 11:53

    To do it in .NET 2.0 (no LINQ), e.g. for ReportingServices without writing a function for it:

    C#

    string a = "", b = "b", c = "", d = "d", e = "";
    string lala = string.Join(" / ",
        string.Join("\u0008", new string[] { a, b, c, d, e }).Split(new char[] { '\u0008' }, System.StringSplitOptions.RemoveEmptyEntries)
    );
    
    System.Console.WriteLine(lala);
    

    VB.NET

    Dim a As String = "", b As String = "b", c As String = "", d As String = "d", e As String = ""
    Dim lala As String = String.Join(" / ", String.Join(vbBack, New String() {a, b, c, d, e}).Split(New Char() {ControlChars.Back}, System.StringSplitOptions.RemoveEmptyEntries))
    
    System.Console.WriteLine(lala)
    

    This assumes that the character backspace doesn't occur in your strings (should usually be true, because you can't simply enter this character by keyboard).

    0 讨论(0)
  • 2021-01-17 11:55

    An alternate way of doing this is by using StringSplitOptions.RemoveEmptyEntries:

    e.g.

    string yourString = "The|quick||brown|||fox|is|here";
    char[] delimiter = new char[] { '|' };
    
    string result = string.Join(",", yourString.Split(delimiter, StringSplitOptions.RemoveEmptyEntries));
    

    This gives:

    The,quick,brown,fox,is,here

    @Stefan Steiger:

    string yourString = "echo 'foo' | sed '/foo/d;'";
    

    This gives:

    echo 'foo' , sed '/foo/d;'

    Which is as I would expect. See the dotnetfiddle of it.

    0 讨论(0)
  • 2021-01-17 12:03

    You can use Where in LINQ to select strings which are not empty:

     return string.Join("\n", parts.Where(s => !string.IsNullOrEmpty(s)));
    
    0 讨论(0)
提交回复
热议问题