2014-10-29 111 views
-5

嗯,标题说明了一切。在这种情况下,答复是输出“这是一个”。 Trim有没有一个已知的错误?我在这里唯一的想法是,这与我正在实施fnms作为一种方法有关,尽管我没有看到这个问题?String.TrimStart不修剪虚假空间

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; 
} 
+12

你要做NSTR = nStr.TrimStart(),字符串是不可变 – 2014-10-29 15:49:52

+2

无关,但你的'(NSTR ?? “”)'没有意义。如果'nStr == null','nStr.TrimStart('')'会抛出一个'NullReferenceException',所以如果你到了第三行,你已经知道'nStr'不能是'null'。 – hvd 2014-10-29 15:52:20

+0

@ hvd是的,你是对的。这样制定的唯一原因是因为我只是意识到需要实施它。但是,在此之前,我已将阵列创建作为该方法的第一个任务。 – Wolfish 2014-10-29 15:54:03

回答

9

TrimStartTrimEnd,以及其作用是改变字符串返回改变的字符串中的每个其他方法。由于字符串为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;