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

后端 未结 4 2155
孤独总比滥情好
孤独总比滥情好 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: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.

提交回复
热议问题