This article illustrates the different techniques to remove the suffix from the end of a string in C#.

1. Using String.Substring() method

The recommended solution is to use the String.Substring() method for removing the substring from the end of a string. It returns a substring that starts at a specified character. This method is overloaded to accept the number of characters in the substring, as the second parameter. For example, the following code removes the characters equal to the substring’s length from the end of a string, only if the string end with the substring.

Download  Run Code

2. Using Regex.Replace() method

The Regex.Replace() method is used to replace substrings in a string having a specified pattern with a replacement string. The following code example demonstrates how to use the Regex.Replace() method from the System.Text.RegularExpressions namespace to remove the suffix from the end of a string. Here, $ matches the position after the string’s last character.

Download  Run Code

 
If the regex is static and frequently invoked, consider compiling the regex for performance increase. For example, the following code removes all numeric values at the end of a string:

Download  Run Code

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