使用不区分大小写的EndsWith
方法调用来确定您的字符串是否以要修剪的字符结尾,如果它确实从字符串末尾删除修剪字符串中的字符数。
在一个方法中,它可能看起来像这样:
private string MyTrimEnd(string s, string trimString) {
if (s.EndsWith(trimString, StringComparison.OrdinalIgnoreCase)) {
// A case-insenstive check shows the string ends with the trimString so remove from the
// end of the string the number of characters in the trimString.
// Trim the result to leave no trailing space characters, if required.
return s.Remove(s.Length - trimString.Length).Trim();
} else {
// The check showed the passed string does not end with the trimString so just return the
// passed string.
return s;
}
}
测试和结果:
Console.WriteLine("'{0}'", MyTrimEnd(text1, "where")); // 'My hosue where sun shines'
Console.WriteLine("'{0}'", MyTrimEnd(text2, "where")); // 'My'
Console.WriteLine("'{0}'", MyTrimEnd(text3, "where")); // 'My where I'
Console.WriteLine("'{0}'", MyTrimEnd("WHERE", "where")); // ''
Console.WriteLine("'{0}'", MyTrimEnd("WHE", "where")); // 'WHE'
Console.WriteLine("'{0}'", MyTrimEnd("blablaWHERE", "where")); //'blabla'
Console.WriteLine("'{0}'", MyTrimEnd(string.Empty, "where")); //''
Console.WriteLine("'{0}'", MyTrimEnd("WHEREwherE", "where")); //'WHERE'
或作为扩展方法:
public static string MyTrimEnd(this string s, string trimString) {
if (s.EndsWith(trimString, StringComparison.OrdinalIgnoreCase)) {
return s.Remove(s.Length - trimString.Length).Trim();
} else {
return s;
}
}