Search code examples
c#trim

String.TrimStart does not trim spurious spaces


Well, the title says it all. Reply, in this case, is outputting " This is a". Is there a known bug with Trim? My only thought here is that it is something to do with the fact that I am implementing fnms as a method, although I don't see a problem with that?

string nStr = " This is a test"

string fnms(string nStr)
{
    nStr.TrimStart(' ');  //doesn't trim the whitespace...
    nStr.TrimEnd(' ');
    string[] tokens = (nStr ?? "").Split(' ');
    string delim = "";
    string reply = null;
    for (int t = 0; t < tokens.Length - 1; t++)
    {
        reply += delim + tokens[t];
        delim = " ";
    }
    //reply.TrimStart(' ');        //It doesn't work here either, I tried.
    //reply.TrimEnd(' ');
    return reply;
}

Solution

  • TrimStart and TrimEnd, as well as every other method which acts to change a string return the changed string. They can never change the string in place due to string being immutable.

    nStr = nStr.TrimStart(' ').TrimEnd(' ');
    

    You can simplify this by just calling Trim which trims the start and end of the string

    nStr = nStr.Trim();