Removing consecutive blank lines from StringBuilder

I have a Stringbuilder object that was populated from a text file. How can I test a StringBuilder object and remove consecutive empty strings.

i.e

Line 1: This is my text
Line 2:
Line 3: Another line after the 1st blank one
Line 4: 
Line 5:
Line 6: Next line after 2 blank lines

(Line numbers are for reference only)

The empty line on line 2 is fine, but I would like to delete the duplicated empty line on line 5, etc.

If line 6 was also an empty line for sarge, and line 7 mattered, I would like to delete empty line 5 and empty line 6, so that there will be only one empty line between line 3 and line 7.

Thanks in advance.

+5
source share
3 answers

Do you already have the contents of the file in StringBuilder?

It would be better to read line by line. Sort of:

private IEnumerable<string> GetLinesFromFile(string fileName)
{
  using (var streamReader = new StreamReader(fileName))
  {
    string line = null;
    bool previousLineWasBlank = false;
    while ((line = streamReader.ReadLine()) != null)
    {
      if (!previousLineWasBlank && string.IsNullOrEmpty(line))
      {
        yield return line;
      }

      previousLineWasBlank = string.IsNullOrEmpty(line);
    }
  }
}

( ) :

foreach (var line in GetLinesFromFile("myFile.txt"))
{
  Console.WriteLine(line);
}

. . : , iterator , foreach. ( , , ), , , .

+3

, , .

while(sb.ToString().Contains(Environment.NewLine + Environment.NewLine))
{
    sb = sb.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
}
+3

StringBuilder , . , "string" + "another string" .

I would suggest using .ToString()then Regex.Replacewith a compiled regular expression with flags set to allow multi-line resolution.

You will probably need a search pattern:

(\n[\w-\n]*\n)

And you replace it with an empty string.

Check out Expresso for a great .NET regex tool.

+2
source

All Articles