ediblecode
ediblecode

Reputation: 11971

Using String.Trim() and String.TrimEnd()

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

Answers (5)

christofr
christofr

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

Hybrid
Hybrid

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

mao
mao

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

LukeH
LukeH

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

Ray
Ray

Reputation: 46595

Trim only removes characters from each end of the string. You need to use Replace like

nameInFull = nameInFull.Replace(".", "");

Upvotes: 1

Related Questions