C# 为什么 string.TrimEnd 不只删除字符串中的最后一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17502379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:39:49  来源:igfitidea点击:

Why string.TrimEnd not removing only last character in string

c#stringtrim

提问by James

I have string as below

我有如下字符串

2,44,AAA,BBB,1,0,,,

So now i want to remove only last comma in above string. So i want output as

所以现在我只想删除上面字符串中的最后一个逗号。所以我想输出为

2,44,AAA,BBB,1,0,,

I decided to use TrimeEnd as below

我决定使用 TrimeEnd 如下

str.ToString.TrimEnd(',')

But it removed all the commas after 0. So i get output as below

但它删除了 0 之后的所有逗号。所以我得到如下输出

2,44,AAA,BBB,1,0

Why it removes all the 3 commas after 0? I just need to remove last character in string

为什么它会删除 0 之后的所有 3 个逗号?我只需要删除字符串中的最后一个字符

采纳答案by Jon Skeet

Why it removes all the 3 commas after 0?

为什么它会删除 0 之后的所有 3 个逗号?

Because that's what it's documentedto do:

因为这是记录在案的目的:

Return value:
The string that remains after all occurrences of the characters in the trimCharsparameter are removed from the end of the current string.

返回值:从当前字符串的末尾删除参数中
所有出现的字符后剩余trimChars的字符串。

If you only want the final character removed, you could use:

如果您只想删除最后一个字符,您可以使用:

if (str.EndsWith(","))
{
    str = str.Substring(0, str.Length - 1);
}

Or equivalently:

或等效地:

if (str.EndsWith(","))
{
    str = str.Remove(str.Length - 1);
}

回答by codingbiz

That is expected. String.TrimEndRemoves alltrailing occurrences of a set of characters specified in an array from the current String object

这是预期的。从当前 String 对象中String.TrimEnd删除数组中指定的一组字符的所有尾随出现

The TrimEnd(char[] trimChars)method removes from the current string all trailing characters that are in the trimCharsparameter. The trim operation stops when the first character that is not in trimCharsis encounteredat the end of the string

TrimEnd(char[] trimChars)方法从当前字符串中删除trimChars参数中的所有尾随字符。trimChars在字符串末尾遇到第一个不在的字符时,修剪操作停止

Use this instead:

改用这个:

str = str.EndsWith(",") ? str.Substring(0, str.Length - 1) : str;

回答by Vishal

You can use this:

你可以使用这个:

string s = "2,44,AAA,BBB,1,0,,,";
s = s.Remove(s.Length-1, 1);

回答by m.r226

Remember Please, the TrimEnd() is not an inplace function. You should reassign its result to str:

请记住,TrimEnd() 不是就地函数。您应该将其结果重新分配给str

str = str.TrimEnd(',')