String.TrimStart不会修剪虚假空间

时间:2014-10-29 15:49:09

标签: 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;
}

2 个答案:

答案 0 :(得分:9)

TrimStartTrimEnd,以及用于更改字符串返回更改后的字符串的所有其他方法。由于字符串为immutable,它们永远不会更改字符串。

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

您可以通过调用Trim来调整字符串

的开头和结尾来简化这一过程
nStr = nStr.Trim();

答案 1 :(得分:2)

您需要将TrSStart中的nStr更新为返回的sting,然后对TrimEnd执行相同操作。

        nStr = nStr.TrimStart(' ');
        nStr = nStr.TrimEnd(' ');
        var tokens = (nStr ?? "").Split(' ');
        var 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;
相关问题