C# String TrimEnd()

The TrimEnd() method in C# is used to remove specified characters from the end of a string. It returns a new string with trailing characters removed.

Here’s the syntax for using the TrimEnd() method:

string trimmedString = originalString.TrimEnd([characters]);

The TrimEnd() method takes an optional parameter characters, which specifies the characters to be removed from the end of the string. If no characters parameter is provided, it removes white spaces.

Here’s an example usage:

string originalString = "Hello World!!!";
string trimmedString = originalString.TrimEnd('!', ' '); // Removes exclamation marks and spaces from the end

Console.WriteLine(trimmedString); // Output: "Hello World"

In this example, the TrimEnd() method is called on the originalString to remove exclamation marks (‘!’) and spaces (‘ ‘) from the end of the string. The resulting trimmedString is then printed, which will output “Hello World” without the trailing characters.

Note that the TrimEnd() method does not modify the original string; instead, it returns a new string with the desired modifications. If you want to modify the original string directly, you can reassign the result to the original variable. For example:

originalString = originalString.TrimEnd('!', ' '); // Reassigning the result to the original variable

Return:

The TrimEnd() method in C# returns a new string with trailing characters removed. It does not modify the original string.

C# String TrimEnd() Method Example:

Certainly! Here’s an example that demonstrates the usage of the TrimEnd() method in C#:

using System;

class Program
{
    static void Main()
    {
        string originalString = "   Hello World!   ";
        char[] charactersToTrim = { '!', ' ' };

        string trimmedString = originalString.TrimEnd(charactersToTrim);

        Console.WriteLine("Original String: \"{0}\"", originalString);
        Console.WriteLine("Trimmed String: \"{0}\"", trimmedString);
    }
}

Output:

Original String: "   Hello World!   "
Trimmed String: "   Hello World"

In this example, the originalString variable contains the string " Hello World! ", with leading and trailing spaces. We define an array charactersToTrim that contains the characters we want to remove, which are exclamation marks and spaces.

The TrimEnd() method is then called on originalString with charactersToTrim as the argument. It removes the specified characters from the end of the string and returns a new string assigned to the trimmedString variable.

Finally, we display the original string and the trimmed string using Console.WriteLine(). As you can see from the output, the trailing exclamation mark and spaces are removed from the end of the original string, resulting in the trimmed string " Hello World".