m.nelson0100
m.nelson0100

Reputation: 47

Removing double new lines from StringBuilder

I have some simple code I am playing with in stringbuilder and everything is copying correctly until two environment newlines come in to play. I then wrote some replace code to remove the double blank lines and it does not work. Just trying to see if anyone has a better idea here and what I am missing. Lister is text block header and word is entered textbox.

var listed =
    TxtBlocks.Zip(UserText.DefaultIfEmpty(), (n, w) => new { Lister = n, Word = w });

StringBuilder sb = new StringBuilder();

sb.AppendLine(("*** " + headerBl.Text + " ***").PadLeft(30) + Environment.NewLine);

foreach (var nw in listed)
{
    if (nw.Word.Length > 0)
    {
        if (nw.Lister.Contains("*** Apples ***") || nw.Lister.Contains("*** Oranges ***") ||
           nw.Lister.Contains("*** Mangos ***"))
            sb.Append(Environment.NewLine);
        sb.Append((nw.Lister + "" + nw.Word).Trim() + Environment.NewLine);
    }
}

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

Clipboard.SetDataObject(sb.ToString()); ;

There are a few entry point for user text before the "*** Apples *** insert. If one of those lines is entered it prints fine:

*** header ***

lister0 and word0

*** apples ***
so on...

But if nothing is inserted to the list before the *** apples *** the newlines pile up, so I added the replace to the code but it is not working.

*** header ***


*** apples ***

Upvotes: 1

Views: 169

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112299

Append the headers lazily. (pseudocode)

string lastHeader = null;
foreach (var nw in listed) {
    if (there is an entry point to add) {
        string header = GetHeader();
        if (header != lastHeader) {
            AppendHeader(sb, header);
            lastHeader = header;
        }
        AppendEntryPoint(sb, nw);
    }
}

This prints the header only in case there is at least one entry point.

In case you are appending the headers in an event handler instead of a loop, just convert the lastHeader variable to a class field private string lastHeader; to make it work.

Upvotes: 3

Related Questions