Donate

Remove Last Character Of A String From StringBuilder Added Using AppendLine() In C#

Good afternoon!

In a situtation where you add string values to a StringBuilder object using the AppendLine() method and you want to delete the last character, you might expect that using the Remove() method in the code below will work. But the truth is it does not.
private static void RemoveLastCharacter()
{
	 StringBuilder sb = new StringBuilder();
	 sb.AppendLine("Lorem ipsum dolor sit amet, consectetur adipiscing elit,");
	 sb.AppendLine("sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
	 sb = sb.Remove(sb.Length - 1, 1);
	 Console.WriteLine(sb.ToString());
}
Using Appendline() method to populate the StringBuilder object according to the documentation will also append the default line terminator after the string value to the end of the StringBuilder instance. Since the default line terminator has two characters specifically "\r\n", we need to include those two characters plus the last character of the string. The revised code to remove the last character of the StringBuilder including the default line terminator using the Remove() method is shown below.
private static void RemoveLastCharacter()
{
	 StringBuilder sb = new StringBuilder();
	 sb.AppendLine("Lorem ipsum dolor sit amet, consectetur adipiscing elit,");
	 sb.AppendLine("sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
	 sb = sb.Remove(sb.Length - 3, 3);
	 Console.WriteLine(sb.ToString());
}
Another way which is shorter is to subtract the Length property of the StringBuilder object directly.
private static void RemoveLastCharacterUsingLength()
{
	 StringBuilder sb = new StringBuilder();
	 sb.AppendLine("Lorem ipsum dolor sit amet, consectetur adipiscing elit,");
	 sb.AppendLine("sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
	 sb.Length -= 3;
	 Console.WriteLine(sb.ToString());
}
Output
Remove Last Character Of A String From StringBuilder Added Using AppendLine() In C#


Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations