循环和字符串输出

时间:2013-03-22 18:58:14

标签: c# string loops

您好我有以下代码:

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

感谢任何帮助, 感谢

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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

答案 2 :(得分: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());