我一直都需要这个,并且经常感到沮丧的是Trim(),TrimStart()和TrimEnd()函数不将字符串作为输入.你在一个字符串上调用EndsWith(),并找出它是否以另一个字符串结束,但是如果你想从最后删除它,你必须做子串黑客(或调用Remove()并祈祷它是唯一的例子...)
为什么.NET中缺少这个基本功能?第二,任何关于实现这个的简单方法的建议(最好不是正则表达式路径......)
Yah*_*hia 73
编辑 - 包装成一个方便的扩展方法:
public static string TrimEnd(this string source, string value)
{
if (!source.EndsWith(value))
return source;
return source.Remove(source.LastIndexOf(value));
}
Run Code Online (Sandbox Code Playgroud)
所以你可以做到 s = s.TrimEnd("DEF");
Dan*_*haw 57
TrimEnd()(和其他修剪方法)接受要修剪的字符,但不接受字符串.如果您真的想要一个可以修剪整个字符串的版本,那么您可以创建一个扩展方法.例如...
public static string TrimEnd(this string input, string suffixToRemove,
StringComparison comparisonType) {
if (input != null && suffixToRemove != null
&& input.EndsWith(suffixToRemove, comparisonType)) {
return input.Substring(0, input.Length - suffixToRemove.Length);
}
else return input;
}
Run Code Online (Sandbox Code Playgroud)
然后可以像内置方法一样调用它.
使用Daniel的代码并将其包装在一段时间而不是直接if提供的功能更类似于Microsoft Trim功能:
public static string TrimEnd(this string input, string suffixToRemove)
{
while (input != null && suffixToRemove != null && input.EndsWith(suffixToRemove))
{
input = input.Substring(0, input.Length - suffixToRemove.Length);
}
return input;
}
Run Code Online (Sandbox Code Playgroud)
我敲了这个快速扩展方法.
它不是正面的(我现在无法测试),但理论是合理的.
public static string RemoveLast(this string source, string value)
{
int index = source.LastIndexOf(value);
return index != -1 ? source.Remove(index, value.Length) : source;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45510 次 |
| 最近记录: |