How to remove a suffix from end of string?

leora picture leora · Mar 12, 2011 · Viewed 42.4k times · Source

I want to:

  1. Check a variable and determine if the last 2 characters are "Id"
  2. If yes, remove them.

I can do it with this below, but them it will blow up if there is an "Id" substring other than the end. Is there a RemoveFromEnd() method that takes a number of characters argument?

 if (column.EndsWith("Id"))
 {
       //remove last 2 characters
       column = column.replace("Id", "");
 }

I see this solution: which does this:

column = System.Text.RegularExpressions.Regex.Replace(column, "Id$", "");

but it says it's pretty slow and I am going to be running this code inside a code block that I would like to be extremely fast so I wanted to see if a faster solution is available.

Answer

Jon picture Jon · Mar 12, 2011

String.Substring can do that:

column = column.Substring(0, column.Length - 2);

You can use it to roll your own RemoveFromEnd:

public static string RemoveFromEnd(this string s, string suffix)
{
    if (s.EndsWith(suffix))
    {
        return s.Substring(0, s.Length - suffix.Length);
    }
    else
    {
        return s;
    }
}