循环和字符串输出
本文关键字:输出 字符串 循环 | 更新日期: 2023-09-27 18:05:27
你好,我有以下代码:
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等),但不知道如何输出。
感谢任何帮助,由于
尝试使用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();
不如这样做:
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
创建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());