90

I need this all the time and am constantly frustrated that the Trim(), TrimStart() and TrimEnd() functions don't take strings as inputs. You call EndsWith() on a string, and find out if it ends with another string, but then if you want to remove it from the end, you have to do substring hacks to do it (or call Remove() and pray it is the only instance...)

Why is this basic function is missing in .NET? And second, any recommendations for a simple way to implement this (preferably not the regular expression route...)

5
  • 5
    Do you want a "ABCDCDCD".TrimEnd("CD") that returns "AB" or a "ABCDCDCD".RemoveIfEndsWith("CD") that returns "ABCDCD"?
    – Guffa
    Commented Aug 24, 2011 at 6:06
  • For my purposes Im interested in the second one - remove a single instance. So I guess the approp name would be RemoveEnd()? An alternative option that can remove all instances of a string, and even take a collection of strings to trim, would be pretty nice too... but different from the current need. I might actually ask another question for that one. Commented Aug 26, 2011 at 14:23
  • 2
    i guess the reason its not there is becuase if all methods that might be useful were added then c# string would become like std:string - full of every imaginable extra including str.DoesSomeofStringMAtchThisLintFromBehindTheSofa(), etc. The fact that c# has a really nice way of adding the methods yourself means this is not really an issue. If you object because it would be more efficient built in instead of a home-brew based substring thingy then I am in deep trouble already considering how often substring gets used in my code.
    – pm100
    Commented Aug 3, 2013 at 23:54
  • 1
    I know the line has to be drawn somewhere, but sheesh this is basic stuff. This, and PickBellyButtonLint(). Commented Aug 5, 2013 at 0:18
  • I agree, this is retarded. Even VB6 could do this, still not added in current versions. Huge oversight ? Technical reason ? .. or just to piss us off ? Commented Mar 28, 2016 at 9:47

12 Answers 12

110

EDIT - wrapped up into a handy extension method:

public static string TrimEnd(this string source, string value)
{
    if (!source.EndsWith(value))
        return source;

    return source.Remove(source.LastIndexOf(value));
}

so you can just do s = s.TrimEnd("DEF");

5
  • your first instance (that doesnt check "endswith" first) i think would empty the whole string if it's not in it? ;) Commented Aug 7, 2012 at 4:13
  • 19
    One line version source.EndsWith(value) ? source.Remove(source.LastIndexOf(value, StringComparison.Ordinal)) : source Commented Nov 2, 2015 at 17:17
  • I named this extension method TrimIfEndsWith Commented Sep 29, 2021 at 13:54
  • 1
    if you pass empty string it still removes one character at the end
    – Tanuki
    Commented Oct 14, 2021 at 13:57
  • Condition should be !source.EndsWith(value) || string.IsNullOrEmpty(value)
    – shmnff
    Commented Nov 8, 2023 at 6:10
74

TrimEnd() (and the other trim methods) accept characters to be trimmed, but not strings. If you really want a version that can trim whole strings then you could create an extension method. For example...

public static string TrimEnd(this string input, string suffixToRemove, StringComparison comparisonType = StringComparison.CurrentCulture)
{
    if (suffixToRemove != null && input.EndsWith(suffixToRemove, comparisonType)) 
    {
        return input.Substring(0, input.Length - suffixToRemove.Length);
    }

    return input;
}

This can then be called just like the built in methods.

3
  • 2
    I would suggest wrapping the code in a while as this simulates functionality from the standard Trim function. See my answer for an update to your code Daniel
    – Ryan Amies
    Commented May 22, 2014 at 12:24
  • I think you should rename the method, because the .NET version that accept a char array remove all that characters. Instead you are implementing an overload with a different behavior. Commented Dec 15, 2014 at 21:52
  • 1
    Added StringComparison parameter to be passed in. You could also default this to comparisonType = StringComparison.OrdinalIgnoreCase or whichever one you want Commented Jan 12, 2017 at 23:18
13

Using Daniel's code and wrapping it in a while rather than a straight if gives functionality more akin to the Microsoft Trim function:

public static string TrimEnd(this string input, string suffixToRemove)
{
    while (input != null && suffixToRemove != null && input.EndsWith(suffixToRemove))
    {
        input = input.Substring(0, input.Length - suffixToRemove.Length);
    }
    return input;
}
1
  • 1
    That's a different behaviour than other answers... Try e.g. running in on a string like "exceeded".TrimEnd("ed")
    – Bartosz
    Commented Jul 30, 2019 at 20:20
7

I knocked up this quick extension method.

Not positive it works (I can't test it right now), but the theory is sound.

    public static string RemoveLast(this string source, string value)
    {
        int index = source.LastIndexOf(value);
        return index != -1 ? source.Remove(index, value.Length) : source;
    }
2
  • 1
    it removes the last occurence but it doesn't make sure that the last occurence is also the end of the string (see OPs post regarding EndsWith)...
    – Yahia
    Commented Aug 24, 2011 at 5:56
  • Yahia: Ah, didn't realise that was part of the requirements. :) Reading comprehension fail. Commented Aug 24, 2011 at 6:04
4

This is what you object to having to do?

if (theString.endsWith(theOtherString))
{
   theString = theString.Substring(0, theString.Length - theOtherString.Length);
}
4
  • 3
    I think this is what the OP called a "substring hack" Commented Aug 24, 2011 at 5:44
  • I agree with boomhauer that this functionality could be provided in the String class as an overload. However, it's hardly a big deal and can be handled in a utility class so as not to be "constantly frustrated" with having to type this.
    – Zesty
    Commented Aug 24, 2011 at 5:50
  • The OP wants a substring, but doesn't want to use the Substring method -- and I'm the one with the downvote? Well, whatever... :-)
    – Ben M
    Commented Aug 24, 2011 at 5:51
  • 1
    I think what frustrates me most about this is, we already have the Trim() functions, why didnt they allow it to also accept a string. Pretty simple option, and immensely useful... Commented Aug 26, 2011 at 14:18
4

Regex replace may be your friend in this instance.

var str = "Hello World!";
str = Regex.Replace(str, @"World!$", "");
//str == "Hello"
1
  • 2
    Regex is generally more resource intensive than normal string methods.
    – bradlis7
    Commented Oct 17, 2018 at 18:06
3

I like my TrimEnd to remove all the instances of the string at the end and not just the last one.

public static string TrimEnd(this string str, string trimStr)
{
    if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(trimStr)) return str;

    while(str.EndsWith(trimStr))
    {
        str = str.Remove(str.LastIndexOf(trimStr));
    }
    return str;
}
2

Yet another version of TrimSuffix string extention method with nullable strings and optional StringComparison parameter:

public static string? TrimSuffix(this string? toTrim, string? suffix, StringComparison comparison = StringComparison.OrdinalIgnoreCase)
{
    if (toTrim == null || suffix == null) return toTrim;

    while(toTrim.EndsWith(suffix)) 
    {
        toTrim = toTrim.Remove(toTrim.LastIndexOf(suffix, comparison));
    }

    return toTrim;
}
1

I recently needed a high performance way to remove single or multiple instances of a string from the start/end of a string. This implementation I came up with is O(n) on the length of the string, avoids expensive allocations, and does not call SubString at all by using a span.

No Substring hack! (Well, now that I edited my post).

    public static string Trim(this string source, string whatToTrim, int count = -1) 
        => Trim(source, whatToTrim, true, true, count);

    public static string TrimStart(this string source, string whatToTrim, int count = -1) 
        => Trim(source, whatToTrim, true, false, count);

    public static string TrimEnd(this string source, string whatToTrim, int count = -1) 
        => Trim(source, whatToTrim, false, true, count);

    public static string Trim(this string source, string whatToTrim, bool trimStart, bool trimEnd, int numberOfOccurrences)
    {
        // source.IsNotNull(nameof(source));  <-- guard method, define your own
        // whatToTrim.IsNotNull(nameof(whatToTrim));  <-- "

        if (numberOfOccurrences == 0 
            || (!trimStart && !trimEnd) 
            || whatToTrim.Length == 0 
            || source.Length < whatToTrim.Length)
            return source;

        int start = 0, end = source.Length - 1, trimlen = whatToTrim.Length;

        if (trimStart)
            for (int count = 0; start < source.Length; start += trimlen, count++)
            {
                if (numberOfOccurrences > 0 && count == numberOfOccurrences)
                    break;
                for (int i = 0; i < trimlen; i++)
                    if ((source[start + i] != whatToTrim[i] && i != trimlen) || source.Length - start < trimlen)
                        goto DONESTART;
            }

        DONESTART:
        if (trimEnd)
            for (int count = 0; end > -1; end -= trimlen, count++)
            {
                if (numberOfOccurrences != -1 && count == numberOfOccurrences)
                    break;

                for (int i = trimlen - 1; i > -1; --i)
                    if ((source[end - trimlen + i + 1] != whatToTrim[i] && i != 0) || end - start + 1 < trimlen)
                        goto DONEEND;
            }

        DONEEND:
        return source.AsSpan().Slice(start, end - start + 1).ToString();
    }
3
  • While this might work it's not very readable. I don't think I've ever seen a goto in C# Commented Sep 10, 2022 at 5:59
  • Goto's are rare to be sure. I only use them in small bits of code. To each their own. This code's been unit tested and will doubtfully even need to be read often. Generally, I do favor readability because code is read more than written.
    – Kit
    Commented Sep 12, 2022 at 0:07
  • Adding an optional StringComparison would be nice. Also worth checking whether the start and end have changed, otherwise you can just return source rather than creating a new string Commented Jun 5, 2023 at 20:57
0

Trim(), TrimStart() and TrimEnd() are methods which replace all occurrences of the same character. That means you can only remove a series of blanks or a series of dots for example.

You could use a regular expression replace in order to accomplish this:

string s1 = "This is a sentence.TRIMTHIS";
string s2 = System.Text.RegularExpressions.Regex.Replace(s1, @"TRIMTHIS$", "");

You could wrap it in an extension method for convenience:

public static string TrimStringEnd(this string text, string removeThis)
{
    return System.Text.RegularExpressions.Regex.Replace(s1, removeThis, "");
}

And call it this way

string s2 = (@"This is a sentence.TRIMTHIS").TrimStringEnd(@"TRIMTHIS");
2
  • 1
    The OP did mention he preferred something that didn't use regexes Commented Aug 24, 2011 at 5:46
  • Remember also that you'll have to escape removeThis. As in Regex.Replace(s1, Regex.Escape(removeThis), ""). Otherwise you'll get regex matching behavior rather than string matching behavior. Commented Aug 12, 2013 at 20:02
0

Here's the extension method I came up with (heavy inspiration taken from existing answers to this question) to complement the existing TrimEnd method; it takes an optional bool allowing for only removing one trailing instance of the string instead of all trailing instances.

/// <summary>
/// Removes trailing occurrence(s) of a given string from the current System.String object.
/// </summary>
/// <param name="trimSuffix">A string to remove from the end of the current System.String object.</param>
/// <param name="removeAll">If true, removes all trailing occurrences of the given suffix; otherwise, just removes the outermost one.</param>
/// <returns>The string that remains after removal of suffix occurrence(s) of the string in the trimSuffix parameter.</returns>
public static string TrimEnd(this string input, string trimSuffix, bool removeAll = true) {
    while (input != null && trimSuffix != null && input.EndsWith(trimSuffix)) {
        input = input.Substring(0, input.Length - trimSuffix.Length);

        if (!removeAll) {
            return input;
        }
    }

    return input;
}
-1

As far as why the function you want is missing, I suspect it's because the designers didn't see it to be as common or as basic as you think it is. And as you've seen from the other answers, it's an easy enough thing to duplicate.

Here's the method I use to do it.

public static string TrimEnd(string input, string suffixToRemove)
{
    if (input == null)
        throw new ArgumentException("input cannot be null.");
    if (suffixToRemove == null)
        throw new ArgumentException("suffixToRemove cannot be null.");
    int pos = input.LastIndexOf(suffixToRemove);
    if (pos == (input.Length - suffixToRemove.Length))
        return input.Substring(0, pos);
    return input;
}
1
  • -1 sorry, SO MANY EXCEPTIONS. Exceptions are for... exceptional cases. Trying to trim a string that is null or with a null suffix is not exceptional, it is rather expected actually. Commented Aug 20, 2014 at 18:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.