How to remove a suffix from end of string?
Solution 1:
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;
}
}
Solution 2:
An alternative to the SubString
method is to use a Regex.Replace
from System.Text.RegularExpressions
:
using System.Text.RegularExpressions;
...
column = Regex.Replace(column, @"Id$", String.Empty);
This way enables you to avoid the test, but not sure if it is really a speed benefit :-). At least an alternative that might be useful in some cases where you need to check for more than one thing at a time.
The regex can be compiled and re-used to get some performance increase and used instead of the call to the static method and can be used like this:
// stored as a private member
private static Regex _checkId = new Regex(@"Id$", RegexOptions.Compiled);
...
// inside some method
column = _checkId.Replace(column, String.Empty);
Solution 3:
Well, there can be a RemoveFromEnd()
method if you write your own:
public static string RemoveFromEnd(this string str, string toRemove)
{
if (str.EndsWith(toRemove))
return str.Substring(0, str.Length - toRemove.Length);
else
return str;
}
You can just use it as follows:
column = column.RemoveFromEnd("Id");
Solution 4:
Since you know the length of the part to remove, you can use Substring
:
if (column.EndsWith("Id"))
{
column = column.Substring(0, column.Length - 2);
}