Remove specific character from the end of a string in C#
This article illustrates the different techniques to remove a specific character from the end of a string in C#.
1. Using String.TrimEnd() method
We can use the String.TrimEnd() method to remove all occurrences of a character from the end of a string. For example, if the character is , and the current string is "a,b,c,", the TrimEnd() method returns "a,b,c". The following example illustrates a simple call to the TrimEnd() method that deletes an extra separator from the end of the string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string s = "a,b,c,,"; char trimChar = ','; s = s.TrimEnd(trimChar); Console.WriteLine(s); // a,b,c } } |
2. Using String.Substring() method
An alternative to the TrimEnd() method for removing only the “last” character is to use a String.Substring() method. It returns a substring that starts at the specified position and continues to the end of the string or the specified position. For example, the following code removes the last character from the string, only if the string end with it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { string s = "a,b,c,,"; char trimChar = ','; if (s.EndsWith(trimChar)) { s = s.Substring(0, s.LastIndexOf(trimChar)); } Console.WriteLine(s); // a,b,c, } } |
3. Using String.Remove() method
Another option to remove only the “last” character is using the String.Remove() method. It returns a new string with the specified number of characters, beginning at a specified position, and is deleted from the original string. For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { string s = "a,b,c,,"; char trimChar = ','; if (s.EndsWith(trimChar)) { s = s.Remove(s.LastIndexOf(trimChar), 1); } Console.WriteLine(s); // a,b,c, } } |
That’s all about removing a specific character 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 :)