0"; str = str.TrimEnd("0".ToCharArr" /> 0"; str = str.TrimEnd("0".ToCharArr" /> 0"; str = str.TrimEnd("0".ToCharArr"/>

Why TrimEnd() function of C# behaves like following?

148 views Asked by At

A simple code snippet is as follows:

public static void Main()
{
    string str = "IsRecorded<code>0</code>";
    str = str.TrimEnd("<code>0</code>".ToCharArray());
    Console.WriteLine(str);
}

The output string that I get is IsRecor. Why does the TrimEnd function strips of ded from the string when it is supposed to strip only <code>0</code>. Also if I reduce the str to IsRec then it gives IsR as output. Why is this happening?

4

There are 4 answers

0
Jon Skeet On BEST ANSWER

The parameter for TrimEnd specifies the set of characters to be trimmed. It's not meant to be a suffix to be trimmed.

So you're saying you want to trim any character in the set { '<', 'c', 'o', 'd', 'e', '>', '0', '/' }. The letters "ded" are all in that set, so they're being trimmed.

If you want to remove a suffix, don't use TrimEnd. Use something like this:

public static string RemoveSuffix(string input, string suffix) =>
    input.EndsWith(suffix, StringComparison.Ordinal)
        ? input.Substring(0, input.Length - suffix.Length)
        : input;

(The string comparison part is important to avoid "interesting" culture-specific effects in some cases. It basically does the simplest match possible.)

2
SomeRandomGuy On

Try this instead :

        string str = "IsRecorded<code>0</code>";
        str = str.Substring(0, str.IndexOf("<code>0</code>"));
        Console.WriteLine(str);
0
Prasad Telkikar On

You can use .LastIndexOf() & Remove() to remove string which is at the end

string str = "IsRecorded<code>0</code>";
str = str.Remove(str.LastIndexOf("<code>0</code>"));

.LastIndexOf(string param) : This will find index of last occurrence of specified string.

.Remove(int startIndex) : Remove string from given index

0
Eduardo Gadotti On

Another solution could be:

string str = "IsRecorded<code>0</code>";
str = str.Replace("<code>0</code>", "");
Console.WriteLine(str);

PS: I know that wont trim just the end part, but if it's not a problem then it could be used