Removing all whitespace lines from a multi-line string efficiently

前端 未结 19 2105
名媛妹妹
名媛妹妹 2020-12-29 04:25

In C# what\'s the best way to remove blank lines i.e., lines that contain only whitespace from a string? I\'m happy to use a Regex if that\'s the best solution.

EDIT

19条回答
  •  無奈伤痛
    2020-12-29 04:47

    Using LINQ:

    var result = string.Join("\r\n",
                     multilineString.Split(new string[] { "\r\n" }, ...None)
                                    .Where(s => !string.IsNullOrWhitespace(s)));
    

    If you're dealing with large inputs and/or inconsistent line endings you should use a StringReader and do the above old-school with a foreach loop instead.

提交回复
热议问题