2013-03-22 66 views
0

嗨,我有以下代碼:循環和字符串輸出

static void CalcWordchange() 
{ 
    List<string[]> l = new List<string[]> 
     { 
     new string[]{Question1, matcheditalian1}, 
     new string[]{"Sam", matcheditalian2}, 
     new string[]{"clozapine", matcheditalian3}, 
     new string[]{"flomax", matcheditalian4}, 
     new string[]{"toradol", matcheditalian5}, 
     }; 

    foreach (string[] a in l) 
    { 
     int cost = LevenshteinDistance.Compute(a[0], a[1]); 
     errorString = String.Format("To change your input: \n {0} \n into the correct word: \n {1} \n you need to make: \n {2} changes \n ".Replace("\n",  Environment.NewLine), 
      a[0], 
      a[1], 
      cost); 
    } 
} 

每次點擊按鈕在foreach循環運行的文本輸出單句(列表中的最後一項)。我想要發生的是將所有5個項目輸出到一個字符串。

我已經添加了4個新變量(errorString2,3等),但無法解決如何輸出它。

任何幫助表示讚賞,感謝

回答

5

嘗試使用StringBuilder對象,收集所有的部件。

StringBuilder buildString = new StringBuilder(); 
foreach (string[] a in l) 
{ 
    int cost = LevenshteinDistance.Compute(a[0], a[1]); 
    buildString.AppendFormat("To change your input: \n {0} \n into the correct word: \n {1} \n you need to make: \n {2} changes \n ".Replace("\n",  Environment.NewLine), 
     a[0], 
     a[1], 
     cost); 
} 
errorString = buildString.ToString(); 
+0

'buildString.AppendLine'與'string + ='有什麼不同?我假設這是一個更好的優化速度與您在我的文章中引用的連接相比較? – wjhguitarman 2013-03-22 19:12:24

+1

@wjhguitaritar:是的。字符串連接創建並拋出一堆臨時字符串。 'StringBuilder'預先分配一個緩衝區並將幾個項目寫入它,然後擴展緩衝區,如果它運行。所以速度更快,使用更少的內存。 – 2013-03-22 19:20:36

+1

@wjhguitarman:字符串串聯每次使用時都會創建一個新字符串(即每次通過循環),其中StringBuilder在幕後使用自增長字符[],直到您調用.ToString())。如果沒有空間,那麼StringBuilder將創建一個新數組,它的大小是舊數組的兩倍。這意味着需要重新創建數組需要的時間越來越長,而不是每循環一次都有一個新的字符串對象。字符串對於非循環而言,Concatination仍然很有用,特別是如果您只是將2-4個字符串加在一起。 – Tory 2013-03-22 19:33:45

2

而是做這樣的事情:

string finalOuput = string.empty; 
foreach (string[] a in l) 
{ 
    int cost = levelshteinDstance.Compute(a[0], a[1]); 
    finalOutput += string.Format("To change your input: \n {0} \n into the correct word: \n {1} \n you need to make: \n {2} changes \n ".Replace("\n",  Environment.NewLine), 
      a[0], 
      a[1], 
      cost); 
    } 
} 

//顯示finalOutput這裏

+3

請不要推薦的字符串連接在一個循環。 – 2013-03-22 19:02:51

1

創建List<string>保持輸出:

var OutputList = new List<string>(); 
foreach (string[] a in l) 
{ 
    errorString = ... 
    OutputList.Add(errorString); 
} 

// output 
foreach (var s in OutputList) 
{ 
    Console.WriteLine(s); 
} 

或者你可以使用一個StringBuilder

var outputS = new StringBuilder(); 
foreach (string[] a in l) 
{ 
    errorstring = ... 
    outputS.AppendLine(errorString); 
} 

Console.WriteLine(outputS.ToString());