Removing Trailing Characters from Strings in C# using `TrimEnd()`

Learn how to efficiently remove trailing characters from strings in C# using the `TrimEnd()` method. This tutorial explains its functionality, demonstrates its usage with various character sets, and highlights its application in data cleaning and string manipulation.



Removing Trailing Characters from Strings in C# with `TrimEnd()`

Understanding `String.TrimEnd()`

The C# `TrimEnd()` method creates a new string by removing all trailing occurrences of specified characters from the end of the original string. "Trailing" means that the characters to remove must be present at the very end of the string. The original string remains unchanged; a new string with the trailing characters removed is returned. This method is useful for cleaning up strings, removing unwanted whitespace or other characters that might appear at the end of a string.

`String.TrimEnd()` Syntax

The syntax is:

public string TrimEnd(params char[] trimChars);

It takes an array of characters (`trimChars`) as input and returns a new string with those characters removed from the end.

Example: Removing Trailing Characters

This example removes the '#' character from the end of the string "Hello C#".

C# Code

using System;

public class TrimEndExample {
    public static void Main(string[] args) {
        string str = "Hello C#";
        string trimmedStr = str.TrimEnd('#');
        Console.WriteLine(trimmedStr); // Output: Hello C
    }
}

Conclusion

The `TrimEnd()` method provides a simple and efficient way to remove trailing characters from strings in C#. This can be beneficial for data cleanup and string formatting tasks. Remember that it returns a new string, leaving the original string unchanged.