2012-12-04 31 views
0

如何在此代碼中使用StringBuilder。如何在循環完成的代碼中使用StringBuilder

 string strFunc = "data /*dsdsds */ data1 /*sads dsds*/"; 
     while (strFunc.Contains("/*")) 
     { 
      int tempStart = strFunc.IndexOf("/*"); 
      int tempEnd = strFunc.IndexOf("*/", tempStart); 

      if (tempEnd == -1) 
      { 
       tempEnd = strFunc.Length; 
      } 
      strFunc = strFunc.Remove(tempStart, tempEnd + 1 - tempStart); 
     } 

邏輯是從字符串

+1

將字符串拆分爲「/ *」?這會給你一個循環的元素數組,並添加到字符串/ – CR41G14

+1

爲什麼你不使用正則表達式?例如,'strFunc = Regex.Replace(strFunc,@「/\*.+?\*/」,「」);' – aquinas

+0

或者有替換函數? – CR41G14

回答

3

刪除命令的數據,你想要做的是一樣的東西

string strFunc = "data /*dsdsds */ data1 /*sads dsds*/"; 
Regex reg = new Regex(@"/\*.+?\*/"); 
strFunc = reg.Replace(strFunc, String.Empty); 

沒有StringBuilder這裏需要。

然而,爲了提供一個例子來使用StringBuilder的:打造其持有刪除「命令」的字符串,你可以寫

MatchCollection commands = reg.Matches(strFunc); 
StringBuilder sb = new StringBuilder(); 
foreach (Match m in commands) 
    sb.Append(m.ToString()); 

但你必須要小心格式化這裏的。

我希望這會有所幫助。

+0

謝謝我試試這個 – user958539