在TrimEnd 3.5下,我得到了与.NET ()不一致的结果。TrimEnd似乎很容易使用,是我做错了什么,还是这是一个bug?
成功案例
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发布于 2012-10-02 19:23:45
也许你可以为此写你自己的方法:
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);
}
}发布于 2012-10-02 19:11:40
您不是从末尾移除确切的字符串,而是从字符串的末尾移除每个字符“.”、“c”、“a”、“t”、“e”、“r”等等。".chattermailcom"碰巧有local中的所有字母,但是".chatter.com"没有(关键的字母是l)。
如果希望从末尾删除整个字符串,请考虑使用EndsWith进行检查,如果为真,则使用substring。
您还可以考虑完全避免字符串操作,并使用URI类;它可以为您解析整个URL并返回各种组件。
发布于 2012-10-02 19:12:15
根据文档,TrimEnd从字符串的末尾移除您传递的数组中的所有字符。对于第二种情况,"d“不是数组的一部分,因此方法将在这里停止。
https://stackoverflow.com/questions/12696666
复制相似问题