使用的情況下,鈍感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;
}
}
謝謝......爲了別人的利益,你還可以用簡單的英語解釋邏輯嗎? (就像什麼是檢查條件) – Lijo
@Lijo當然,我會在一分鐘內編輯我的帖子 – horgh