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

To remove characters from the end of an immutable string, we must create a new string object with removed characters. We can do this in multiple ways in C#:

1. Using range operator ..

Starting C# 8, we can use the range operator .., which specifies the start and end of a range as its operands. The following code example demonstrates its usage to remove certain characters from the end of a string:

Download  Run Code

2. Using String.Remove() method

Another recommended solution to remove a range of characters from a string is to use its built-in Remove() method. The following example demonstrates its usage.

Download  Run Code

3. Using String.Substring() method

To remove the n characters from the end of a string, we can use its String.Substring() method where we pass the starting index as 0 and the ending index n less than the string length.

Download  Run Code

 
The above solution will throw an ArgumentOutOfRangeException if the index is out of range. The index must be non-negative and less than the length of the string. This is handled in the following code:

Download  Run Code

4. Using String.ToCharArray() method

Here, the idea is to use the String.ToCharArray() method that takes a range and copies the characters in the specified range to a character array.

Download  Run Code

 
The above solution will throw an ArgumentOutOfRangeException if the index is negative or more than the string’s length. This can be handled, as demonstrated below:

Download  Run Code

5. LINQ Skip() method

LINQ Skip() method is used to skip certain characters in the string from the beginning. To skip characters from the end of the string, we have to reverse the string before calling the Skip() method. After skipping the required characters, reverse the string again. This solution performs slower than all the above solutions.

The following code example shows how to implement this using the String.Concat.

Download  Run Code

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