我试着编写一个简单的程序,它将从2个文本框中获取2个多行输入,将它们放在2个数组中并进行比较.
我想检查数组1中的条目(文本框1的每一行是数组1中的单独条目)是否在数组2中(文本框2的每一行是数组2中的单独条目).
然后将结果输出到文本框.
例如:
数组1"一,二,三,四,六"
阵列2"一,三,五,四"
它应该输出:
one = found
two = not found
three = found
four = found
six = not found
Run Code Online (Sandbox Code Playgroud)
我到目前为止的代码如下:
private void button1_Click(object sender, EventArgs e)
{
textBox3.Text = "";
string[] New = textBox1.Text.Split('\n');
string[] Existing = textBox2.Text.Split('\n');
//for each line in textbox1's array
foreach (string str in New)
{
//if the string is present in textbox2's array
if (Existing.Contains(str))
{
textBox3.Text = " ##" + textBox3.Text + str + "found";
}
/if the string is not present in textbox2's array
else
{
textBox3.Text = " ##" +textBox3.Text + str + "not found";
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果在任一文本框中有多行,则无法正常工作 - 我无法弄清楚为什么......测试运行中会发生以下情况:
Array 1 - "One"
Array 2 - "One"
Result = One Found
Array 1 - "One"
Array 2 - "One, Two"
Result = One Not Found
Array 1 - "One, Two"
Array 2 - "One, Two"
Result = One found, Two Found
Array 1 - "One, Two, Three"
Array 2 - "One, Two"
Result - One Found, Two Not Found, Three Not Found
Run Code Online (Sandbox Code Playgroud)
提前致谢
如果任一文本框中有多行,这是行不通的 - 有人能找出原因吗?
您应该自己诊断问题 - 我怀疑在循环之前的一个简单断点,通过检查数组,会立即发现问题.
我很确定问题只是你应该分开"\r\n"而不是'\n'- 目前你最终会\r在除了最后一行之外的所有行的末尾都有一个流氓,这会弄乱结果.
Text您可以只使用该Lines属性,而不是使用该属性然后拆分它:
string[] newLines = textBox1.Lines;
string[] existingLines = textBox2.Lines;
...
Run Code Online (Sandbox Code Playgroud)
编辑:如Guffa的回答所述,您还希望避免textBox3.Text在每次迭代时进行替换.我个人可能会使用create a List<string>,在每次迭代时添加它,然后在最后使用:
textBox3.Lines = results.ToArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3995 次 |
| 最近记录: |