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

12,112

Solution 1

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.

Solution 2

You can access any character of your StringBuilder with its index, like you would with a String.

var sb = new StringBuilder();
sb.Append("Hello world!\n");
Console.WriteLine(sb[sb.Length - 1] == '\n'); // True

Solution 3

You can normalize the newlines, using a regex:

var test = @"hello

moop

hello";

var regex = new Regex(@"(?:\r\n|[\r\n])+");

var newLinesNormalized = regex.Replace(test, Environment.NewLine);

output:

hello
moop
hello

Solution 4

Single line check. Uses a string type, not StringBuilder, but you should get the basic idea.

if (theString.Substring(theString.Length - Environment.NewLine.Length, Environment.NewLine.Length).Contains(Environment.NewLine))
{
     //theString does end with a NewLine
}
else
{
     //theString does NOT end with a NewLine
}
Share:
12,112
Noich
Author by

Noich

SOreadytohelp Linux drivers developers. Toys with C, yeah! Formerly a C# developer. Toys with WPF, EF, SQL, Python and other fun stuff.

Updated on July 26, 2022

Comments

  • Noich
    Noich almost 2 years

    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.)