0

我正在尝试编写一个简单的程序,该程序将从 2 个文本框中获取 2 个多行输入,将它们放入 2 个数组中并进行比较。

我想检查数组 1 中的条目(文本框 1 的每一行是数组 1 中的单独条目)是否在数组 2 中(文本框 2 的每一行都是数组 2 中的单独条目)。

然后将结果输出到文本框。

例如:

数组 1“一、二、三、四、六”

数组 2“一、三、五、四”

它应该输出:

one = found
two = not found
three = found
four = found
six = not found

我到目前为止的代码如下:

 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";
            }
        }


    }

如果任一文本框中有不止一行,这将无法正常工作 - 我无法弄清楚为什么..在测试运行中发生以下情况:

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

提前致谢

4

4 回答 4

5

如果任一文本框中有不止一行,这将无法正常工作 - 任何人都可以找出原因吗?

您应该自己诊断问题 - 我怀疑循环之前的一个简单断点,然后检查数组,会立即发现问题。

我很确定问题只是你应该分开"\r\n"而不是'\n'- 目前你最终会\r在除最后一行之外的所有行的末尾遇到一个流氓,这会弄乱结果。

您可以只使用该属性,而不是使用该Text属性然后拆分它Lines

string[] newLines = textBox1.Lines;
string[] existingLines = textBox2.Lines;
...

编辑:正如 Guffa 的回答中所述,您希望避免textBox3.Text在每次迭代时进行替换。就个人而言,我可能会使用 create a List<string>,在每次迭代时添加它,然后在最终使用时:

textBox3.Lines = results.ToArray();
于 2012-05-30T19:07:28.023 回答
1

使用武力,卢克:

char[] delimiterChars = { ' ', ',', '.', ':', '\t', '\n', '\r' };
string[] words = text.Split(delimiterChars);

在分隔符中添加了 '\r'。

于 2012-05-30T19:07:17.107 回答
1

您可以尝试此代码(只需将 更改intstring):

var a = Enumerable.Range(1, 10);
var b = new[] { 7, 8, 11, 12 };

// mixing the two arrays, since it's a ISet, this will contain unique values
var c = new HashSet<int>(a);
b.ToList().ForEach(x => c.Add(x));

// just project the results, you can iterate through this collection to 
// present the results to the user
var d = c.Select(x => new { Number = x, FoundInA = a.Contains(x), FoundInB = b.Contains(x) });

产生:

在此处输入图像描述

于 2012-05-30T19:28:32.533 回答
1
string[] New = textBox1.Text.Split(',').Select(t => t.Trim()).ToArray();
string[] Existing = textBox2.Text.Split(',').Select(t => t.Trim()).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var str in New)
{
    sb.AppendLine(str + (Existing.Contains(str) ? " found" : " not found"));
}
textBox3.Text = sb.ToString();
于 2012-05-30T19:34:16.753 回答