如果它以","结束,我想修剪一个字符串的结尾.那是逗号和空格.
我试过了TrimEnd(', '),但这不起作用.它必须只有字符串以这种方式结束,所以我不能只使用.Remove删除最后两个字符.我该怎么做?
Hen*_*man 27
string txt = "testing, ";
txt = txt.TrimEnd(',',' '); // txt = "testing"
Run Code Online (Sandbox Code Playgroud)
这使用了过载 TrimEnd(params char[] trimChars).您可以指定一个或多个将形成要删除的字符集的字符.在这种情况下逗号和空格.
这应该工作:
string s = "Bar, ";
if (s.EndsWith(", "))
s = s.Substring(0, s.Length - 2);
Run Code Online (Sandbox Code Playgroud)
编辑
想想看,这将成为一个很好的扩展方法:
public static String RemoveSuffix(this string value, string suffix)
{
if (value.EndsWith(suffix))
return value.Substring(0, value.Length - suffix.Length);
return value;
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
string someText = "some text, ";
char[] charsToTrim = { ',', ' ' };
someText = someText.TrimEnd(charsToTrim);
Run Code Online (Sandbox Code Playgroud)
适合我.
| 归档时间: |
|
| 查看次数: |
19857 次 |
| 最近记录: |