Reputation: 61463
I'm getting inconsistent results with TrimEnd() under .NET 3.5. TrimEnd seems so simple to use, is there something I'm doing wrong here or is this a bug
Success case
var foundvalue = "hosted.local.chatter.com";
Console.WriteLine(foundvalue.TrimEnd(".chatter.com".ToCharArray()));
// Result is "hosted.local" which is expected.
Failure case
var foundvalue = "hosted.local.chattermailcom";
Console.WriteLine(foundvalue.TrimEnd(".chattermailcom".ToCharArray()));
// Result is "hosted" which is incorrect
Upvotes: 1
Views: 258
Reputation: 61952
Maybe you could write your own method for that:
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);
}
}
Upvotes: 4
Reputation: 4893
TrimEnd is not designed to strip a string off. The word "local" contains all characters that are in your trimEnd chars ("chattermailcom" -> includes l, o, c, a, and l). You are getting expected behavior of trimEnd.
The TrimEnd method removes from the current string all trailing characters that are in the trimChars parameter. The trim operation stops when the first character that is not in trimChars is encountered at the end of the string. For example, if the current string is "123abc456xyz789" and trimChars contains the digits from "1" through "9", the TrimEnd method returns "123abc456xyz".
Upvotes: 1
Reputation: 203817
You aren't removing the exact string, ".chattermailcom"
from the end, you're removing each of the characters, '.', 'c', 'a', 't', 'e', 'r', etc. from the end of the string. ".chattermailcom"
happens to have all of the letters in local
, but ".chatter.com"
doesn't (the key letter there being the l
).
If you want to remove the entire string from the end consider using EndsWith
to do the check, and then substring
if it's true.
You could also consider avoiding the string manipulation entirely and using the URI class; it could parse the entire URL for you and return the various components.
Upvotes: 11
Reputation: 4232
As per documentation, TrimEnd
removes all characters from the end of the string which are in the array you've passed. For the second case, the "d" is not part of the array so the method will stop here.
Upvotes: 6
Reputation: 181
Why does that surprise you? TrimEnd takes an array of characters to remove from the end. You tell it to remove all '.', 'c', 'h', 'a', 't' and so on.. And exactly why you tell it to remove it all characters within the string ".local.", they will be removed. Please read again what TrimEnd() does.
Upvotes: 2