where如果字符串末尾有单词,我需要修剪字符串。C# 中对此执行快速的方法是什么?
注意:要修剪的词可以是任何东西..WHERE只是一个例子
string text1 = "My hosue where sun shines"; //RESULT: "My hosue where sun shines"
string text2 = "My where"; //RESULT: "My"
string text3 = "My where I WHERE"; //RESULT:"My where I"
Run Code Online (Sandbox Code Playgroud)
你可以使用string.EndsWith方法和string.Substring
public static string Trim(this string s, string trimmer)
{
if (String.IsNullOrEmpty(s)|| String.IsNullOrEmpty(trimmer) ||!s.EndsWith(trimmer,StringComparison.OrdinalIgnoreCase))
return s;
else
return s.Substring(0, s.Length - trimmer.Length);
}
Run Code Online (Sandbox Code Playgroud)