2014-10-29 110 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;