String.TrimStart不会修剪虚假空间

Wol*_*ish -5 c# trim

嗯,标题说明了一切.在这种情况下,回复输出"This is a".Trim有一个已知的错误吗?我唯一想到的是,它与我fnms作为一种方法实现的事实有关,虽然我没有看到它的问题?

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;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*iec 9

TrimStart并且TrimEnd,以及用于更改字符串的所有其他方法返回已更改的字符串.由于字符串是不可变的,它们永远不能更改字符串.

nStr = nStr.TrimStart(' ').TrimEnd(' ');
Run Code Online (Sandbox Code Playgroud)

您可以通过调用Trim对字符串的开头和结尾进行修剪来简化此操作

nStr = nStr.Trim();
Run Code Online (Sandbox Code Playgroud)