This post will discuss how to remove characters from the end of a string in C#.

Since strings are immutable in C#, you can’t add or remove characters from a string. However, you can create a new string with the original string remains untouched, using any of the following solutions:

1. Using Ranges

Starting with C# 8, you can use the ranges .. to remove characters from the end of a string. It takes the start and end of a range as its operands, and can be elegantly used as follows to remove the last character from the string:

Download  Run Code

 
The above solution throws ArgumentOutOfRangeException if the specified length is more than the length of the string. The following code example creates an extension method, that elegantly handles this.

Download  Run Code

2. Using String.Remove() method

The String.Remove() method removes all the characters in a string, beginning at a specified position and till its end. The following example creates an extension method and removes the last two characters from the given string.

Download  Run Code

3. Using String.Substring() method

Alternatively, you can use the String.Substring() method to retrieve a substring from the string instance. This substring starts from the specified index having the specified length, and it can be used as follows to remove characters from the string’s end.

Download  Run Code

4. Using String.TrimEnd() method

If you need to remove characters from the end of a string only if it matches the specific character, use the String.TrimEnd() method instead. It removes all occurrences of the specified character from the string’s end. The following example demonstrates its usage.

Download  Run Code

 
The above example removes all commas from the end of the string. However, if you want to remove the last instance of the specified character from the string, you can find the last index of that character and pass it to the String.Remove() method:

Download  Run Code

That’s all about removing characters from the end of a string in C#.