比较2个字符串数组C#

时间:2012-05-30 19:02:25

标签: c# arrays string

我试着编写一个简单的程序,它将从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 个答案:

答案 0 :(得分:5)

  

如果任一文本框中有多行,这是行不通的 - 有人能找出原因吗?

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

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

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

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

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

textBox3.Lines = results.ToArray();

答案 1 :(得分:1)

使用武力,卢克:

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

为分隔符添加了'\ r'。

答案 2 :(得分:1)

您可以尝试使用此代码(只需将int更改为string):

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

产生:

enter image description here

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