从字符串中修剪最后一个字符 [英] Trim last character from a string
问题描述
我有一个字符串说
你好!世界!
我想做一个微调或删除取出!过世界,但不脱你好。
世界,你好!TrimEnd('!')。
编辑:
我已经注意到这种类型的相当多每个人都建议删除指定字符串的最后一个字符的问题。但是,这并不符合修剪方法的定义。
修剪 - 删除所有出现 从空格字符 开始与该实例的结束。
根据这一定义从字符串只删除最后一个字符是不好解决。
因此,如果我们想修剪从字符串最后一个字符我们应该做这样的事
实例作为扩展方法:
公共静态类MyExtensions
{
公共静态字符串TrimLastCharacter(此字符串str)
{
如果(String.IsNullOrEmpty(STR)){
返回海峡;
} 其他 {
返回str.TrimEnd(STR [str.Length - 1]);
}
}
}
I have a string say
"Hello! world!"
I want to do a trim or a remove to take out the ! off world but not off Hello.
"Hello! world!".TrimEnd('!');
EDIT:
What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.
Trim - Removes all occurrences of white space characters from the beginning and end of this instance.
Under this definition removing only last character from string is bad solution.
So if we want to "Trim last character from string" we should do something like this
Example as extension method:
public static class MyExtensions
{
public static string TrimLastCharacter(this String str)
{
if(String.IsNullOrEmpty(str)){
return str;
} else {
return str.TrimEnd(str[str.Length - 1]);
}
}
}
这篇关于从字符串中修剪最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!