Search code examples
c#stringtrimtexttrimming

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


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?


Solution

  • 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.)