Search code examples
c#stringbuilder

C# StringBuilder: Check if it ends with a new line


I have a StringBuilder that accumulates code. In some cases, it has 2 empty lines between code blocks, and I'd like to make that 1 empty line.
How can I check if the current code already has an empty line at the end? (I prefer not to use its ToString() method because of performance issues.)


Solution

  • Since I don't care about 2 empty lines in the middle of the code, the simplest way is to use

    myCode.Replace(string.Format("{0}{0}", Environment.NewLine),Environment.NewLine);
    

    This option doesn't require any changes to classes that use the code accumulator.