Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing consecutive blank rows from StringBuilder

Tags:

c#

I have a Stringbuilder object that has been populated from a text file. How can I check the StringBuilder object for and remove consecutive "blank" lines.

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 given as reference only)

The blank line on Line 2 is fine, but I would like to remove the duplicate blank line, on Line 5, and so on.

If for argument sake Line 6 would have also been a blank line, and a Line 7 had a value, I would like Blank Line 5 and Blank Line 6 removed, so that there would only be 1 blank line between the Line 3 and Line 7.

Thanks in advance.

like image 294
Riaan Avatar asked Jul 08 '10 16:07

Riaan


People also ask

How do I remove blank lines in a text file?

In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box. Click the Replace All button to replace all blank lines.

How does StringBuilder work c#?

The StringBuilder works by maintaining a buffer of characters (Char) that will form the final string. Characters can be appended, removed and manipulated via the StringBuilder, with the modifications being reflected by updating the character buffer accordingly. An array is used for this character buffer.


2 Answers

Do you have to already have the file contents in a StringBuilder?

It would be nicer to be able to read line-by-line. Something like:

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);
    }
  }
}

Now you can read in your text (which has had dupe blank lines removed) like this:

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

Note: I'm only illustrating a technique here. There are other considerations: e.g. my iterator method holds the file open while the consumers are processing the foreach. This is nice and memory efficient (more so than reading into a string for example) as you are only dealing with one line at a time, but not ideal for files that take a long time to process.

like image 55
Rob Levine Avatar answered Nov 03 '22 00:11

Rob Levine


Probably not very efficient, but it's easy.

while(sb.ToString().Contains(Environment.NewLine + Environment.NewLine))
{
    sb = sb.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
}
like image 23
Hans Olsson Avatar answered Nov 02 '22 23:11

Hans Olsson