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 等),但无法确定如何输出它。

任何帮助表示赞赏,谢谢

4

3 回答 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();
于 2013-03-22T19:03:50.470 回答
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);
    }
}

//在这里显示最终输出

于 2013-03-22T19:01:50.967 回答
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());
于 2013-03-22T19:04:16.657 回答