I want to trim the end off a string if it ends in ", ". That's a comma and a space.
I've tried TrimEnd(', ')
, but this doesn't work. It has to be only if the string ends this way, so I can't just use .Remove
to remove the last two characters. How can I do it?
string txt = " testing, , ";
txt = txt.TrimEnd(',',' '); // txt = "testing"
This uses the overload TrimEnd(params char[] trimChars)
. You can specify 1 or more chars that will form the set of chars to remove. In this case comma and space.
This should work:
string s = "Bar, ";
if (s.EndsWith(", "))
s = s.Substring(0, s.Length - 2);
EDIT
Come to think of it, this would make a nice extension method:
public static String RemoveSuffix(this string value, string suffix)
{
if (value.EndsWith(suffix))
return value.Substring(0, value.Length - suffix.Length);
return value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With