Reputation: 11971
I am implementing a heuristic for splitting names up into relevant fields (I know it would be easier to received them separated but I'm not). I need to remove all of the '.' characters in the string first, and then split where there are spaces in the string.
Why isn't this removing the '.' in for example Mr. John Doe
public void SplitNamesAndRemovePeriods()
{
char[] period = {'.'};
nameInFull = nameInFull.TrimEnd(period);
string[] allNames = nameInFull.Split(' ');
PrintNames();
}
Thanks
Upvotes: 1
Views: 22725
Reputation: 2700
TrimEnd
removes all trailing occurrences of a set of characters specified in an array from the current String object.
Try:
public void SplitNamesAndRemovePeriods()
{
nameInFull = nameInFull.Replace(".", String.Empty);
string[] allNames = nameInFull.Split(' ');
PrintNames();
}
Upvotes: 1
Reputation: 406
TrimEnd only removes the specified character if it exists at the end of the string.
You probably want to use IndexOf('.') and pass the result to Remove. Do this in a loop until IndexOf fails.
If you'd rather replace the '.' with another character, e.g. ' ', then use Replace instead of Remove.
Upvotes: 0
Reputation: 1404
If you want to remove all the '.' characters in string you'd better use string.Replace() method:
public void SplitNamesAndRemovePeriods()
{
nameInFull = nameInFull.Replace(".", "");
string[] allNames = nameInFull.Split(' ');
PrintNames();
}
Upvotes: 1
Reputation: 269628
Your TrimEnd
call will only remove .
characters found at the end of the string.
If you want to remove all .
characters throughout the string then you should use Replace
instead:
nameInFull = nameInFull.Replace(".", "");
Note that replacing like this could affect the subsequent split operation if your source string is malformed. For example, if the original string is "Mr.Foo.Bar" then the output of the replace operation will be "MrFooBar", with no spaces to split on. To avoid this you could consider replacing with a space rather than an empty string.
Upvotes: 3
Reputation: 46595
Trim only removes characters from each end of the string. You need to use Replace like
nameInFull = nameInFull.Replace(".", "");
Upvotes: 1