Remove suffix from end of a string in C#
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; public static class StringExtensions { public static string RemoveSuffix(this string s, string suffix) { if (s.EndsWith(suffix)) { return s.Substring(0, s.Length - suffix.Length); } return s; } } public class Example { public static void Main() { String s = "HelloWorld"; s = s.RemoveSuffix("World"); Console.WriteLine(s); // Hello } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Text.RegularExpressions; public static class StringExtensions { public static string RemoveSuffix(this string s, string suffix) { return Regex.Replace(s, suffix + "$", String.Empty); } } public class Example { public static void Main() { String s = "HelloWorld"; s = s.RemoveSuffix("World"); Console.WriteLine(s); // Hello } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Text.RegularExpressions; public static class StringExtensions { private static Regex numericRegex = new Regex("\\d+$", RegexOptions.Compiled); public static string RemoveNumericSuffix(this string s) { return numericRegex.Replace(s, String.Empty); } } public class Example { public static void Main() { String s = "Hello123"; s = s.RemoveNumericSuffix(); Console.WriteLine(s); // Hello } } |
That’s all about removing the suffix from the end of a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)