How to remove empty lines from a formatted string?

后端 未结 11 1466
一生所求
一生所求 2020-12-01 02:24

How to remove empty lines in a string in C#? I am generating some text files in C# (winforms) and for some reason there are some empty lines. How can I remove them after the

相关标签:
11条回答
  • 2020-12-01 02:45

    I found simple answer to this problem

    YourradTextBox.Lines = YourradTextBox.Lines.Where(p => p.Length > 0).ToArray();

    Adapted from Marco Minerva [MCPD] at: https://social.msdn.microsoft.com/Forums/windows/en-US/b1bb4107-4ad5-4cd3-bd20-9c2b3f9b31a6/delete-lines-from-multiline-textbox-if-its-contain-certain-string-c?forum=winforms&prof=required

    0 讨论(0)
  • 2020-12-01 02:46

    @Tim Pietzcker - Not working for me. I have to change a little bit but thx!
    Ehhh C# Regex.. I had to change it again but this working good:

    private string RemoveEmptyLines(string lines)
    {
      return Regex.Replace(lines, @"^\s*$\n|\r", string.Empty, RegexOptions.Multiline).TrimEnd();
    }
    

    Example: http://regex101.com/r/vE5mP1/2

    0 讨论(0)
  • 2020-12-01 02:46

    No method mentioned here helped me all the way, but I found a workaround.

    1. Split text to lines - collection of strings (with or without empty strings, also Trim() each string).
    2. Add these lines to multiline string.

    {}

    public static IEnumerable<string> SplitToLines(this string inputText, bool removeEmptyLines = true)
    {
        if (inputText == null)
        {
            yield break;
        }
    
        using (StringReader reader = new StringReader(inputText))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (removeEmptyLines && !string.IsNullOrWhiteSpace(line))
                    yield return line.Trim();
                else
                    yield return line.Trim();
            }
        }
    }
    
    public static string ToMultilineText(this string text)
    {
        var lines = text.SplitToLines();
    
        return string.Join(Environment.NewLine, lines);
    }
    
    0 讨论(0)
  • 2020-12-01 02:49

    You could try String.Replace("\n\n", "\n");

    0 讨论(0)
  • 2020-12-01 02:50
    private string remove_space(string st)
    {
        String final = "";
    
        char[] b = new char[] { '\r', '\n' };
        String[] lines = st.Split(b, StringSplitOptions.RemoveEmptyEntries);
        foreach (String s in lines)
        {
            if (!String.IsNullOrWhiteSpace(s))
            {
                final += s;
                final += Environment.NewLine;
            }
        }
    
        return final;
    }
    
    0 讨论(0)
提交回复
热议问题