【问题标题】:String.TrimStart does not trim spurious spacesString.TrimStart 不修剪虚假空格
【发布时间】:2014-12-25 10:10:19
【问题描述】:

嗯,标题说明了一切。在这种情况下,回复正在输出“这是一个”。 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;
}

【问题讨论】:

  • 你必须做 nStr = nStr.TrimStart(),字符串是不可变的
  • 无关,但您的(nStr ?? "") 没有意义。如果nStr == nullnStr.TrimStart(' ') 会抛出NullReferenceException,所以如果你到第三行,你已经知道nStr 不能是null
  • @hvd 是的,你是对的。如此制定它的唯一原因是因为我刚刚意识到需要实施它。但是,在此之前,我将数组创建作为方法中的第一个任务。
  • 您可以使用nStr = nStr.Trim(); 一次修剪前导和尾随空格。
  • @Sinatr 我认为这会完全删除所有空格?

标签: c# trim


【解决方案1】:

TrimStartTrimEnd,以及用于更改字符串的所有其他方法return 更改后的字符串。由于字符串为immutable,他们永远无法更改字符串。

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

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

nStr = nStr.Trim();

【讨论】:

    【解决方案2】:

    您需要将 nStr 更新为从 TrimStart 返回的字符串,然后对 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;
    

    【讨论】:

      猜你喜欢
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多