从修剪在.NET中字符串的结尾的字符串 - 这是为什么不见了? [英] Trim string from the end of a string in .NET - why is this missing?

查看:131
本文介绍了从修剪在.NET中字符串的结尾的字符串 - 这是为什么不见了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这需要所有的时间和我不断受挫的修剪(),TrimStart()和TrimEnd()函数不采取字符串作为输入。你在一个字符串调用的endsWith(),并找出它是否与另一个字符串结束,但如果你想从最终删除它,你必须做串黑客做(或调用remove()和祈祷,这是的唯一实例...)

I need this all the time and am constantly frustrated that the Trim(), TrimStart() and TrimEnd() functions don't take strings as inputs. You call EndsWith() on a string, and find out if it ends with another string, but then if you want to remove it from the end, you have to do substring hacks to do it (or call Remove() and pray it is the only instance...)

为什么这个基本功能是缺少.NET?第二,一个简单的方法的任何建议来实现这个(最好不要正则表达式的路线...)

Why is this basic function is missing in .NET? And second, any recommendations for a simple way to implement this (preferably not the regular expression route...)

推荐答案

<一个HREF =htt​​p://msdn.microsoft.com/en-us/library/system.string.trimend.aspx> TrimEnd() (和其他装饰方法)接受字符进行修整,但不是字符串。如果你真的想要一个版本,可以修剪整个字符串,那么你可以创建一个扩展方法。例如...

TrimEnd() (and the other trim methods) accept characters to be trimmed, but not strings. If you really want a version that can trim whole strings then you could create an extension method. For example...

public static string TrimEnd(this string input, string suffixToRemove) {
    if (input != null && suffixToRemove != null
      && input.EndsWith(suffixToRemove)) {
        return input.Substring(0, input.Length - suffixToRemove.Length);
    }
    else return input;
}

这可以被称为就像内置的方法。

This can then be called just like the built in methods.

这篇关于从修剪在.NET中字符串的结尾的字符串 - 这是为什么不见了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆