Removing all whitespace lines from a multi-line string efficiently

前端 未结 19 2118
名媛妹妹
名媛妹妹 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:49

    Here's another option: use the StringReader class. Advantages: one pass over the string, creates no intermediate arrays.

    public static string RemoveEmptyLines(this string text) {
        var builder = new StringBuilder();
    
        using (var reader = new StringReader(text)) {
            while (reader.Peek() != -1) {
                string line = reader.ReadLine();
                if (!string.IsNullOrWhiteSpace(line))
                    builder.AppendLine(line);
            }
        }
    
        return builder.ToString();
    }
    

    Note: the IsNullOrWhiteSpace method is new in .NET 4.0. If you don't have that, it's trivial to write on your own:

    public static bool IsNullOrWhiteSpace(string text) {
        return string.IsNullOrEmpty(text) || text.Trim().Length < 1;
    }
    

提交回复
热议问题