我在.NET 3.5下使用TrimEnd()获得了不一致的结果。 TrimEnd看起来好像很简单,有什么我在这里做错了或者这是一个错误
成功案例
var foundvalue = "hosted.local.chatter.com";
Console.WriteLine(foundvalue.TrimEnd(".chatter.com".ToCharArray()));
// Result is "hosted.local" which is expected.
失败案例
var foundvalue = "hosted.local.chattermailcom";
Console.WriteLine(foundvalue.TrimEnd(".chattermailcom".ToCharArray()));
// Result is "hosted" which is incorrect
答案 0 :(得分:10)
你没有从最后删除确切的字符串".chattermailcom"
,你要删除每个字符,'。','c','a','t','e',来自字符串末尾的'r'等。 ".chattermailcom"
碰巧有local
中的所有字母,但".chatter.com"
没有(l
的关键字)。
如果要从最后删除整个字符串,请考虑使用EndsWith
进行检查,然后substring
是否为真。
您还可以考虑完全避免字符串操作并使用URI类;它可以为您解析整个URL并返回各种组件。
答案 1 :(得分:6)
根据documentation,TrimEnd
会删除字符串末尾的所有字符,这些字符位于您传递的数组中。对于第二种情况,“d”不是数组的一部分,因此该方法将在此处停止。
答案 2 :(得分:4)
也许你可以为此编写自己的方法:
public static class Extensions
{
public static string RemoveEnd(this string strBefore, string substringToRemove)
{
if (!strBefore.EndsWith(substringToRemove))
return strBefore;
return strBefore.Remove(strBefore.Length - substringToRemove.Length);
}
}
答案 3 :(得分:2)
为什么会让你感到惊讶? TrimEnd从最后删除一个字符数组。你告诉它删除所有'。','c','h','a','t'等等。正是为什么你告诉它删除字符串“.local。”中的所有字符,他们将被删除。请再读一遍TrimEnd()的作用。
答案 4 :(得分:1)
TrimEnd不是为了剥离字符串而设计的。单词“local”包含trimEnd字符中的所有字符(“chattermailcom” - >包括l,o,c,a和l)。您正在获得trimEnd的预期行为。
TrimEnd方法从当前字符串中删除所有尾随 trimChars参数中的字符。修剪操作 遇到第一个不在trimChars中的字符时停止 在字符串的末尾。例如,如果当前字符串是 “123abc456xyz789”和trimChars包含“1”到“1”的数字 “9”,TrimEnd方法返回“123abc456xyz”。