繁体   English   中英

比较2个字符串数组C#

[英]Comparing 2 String Arrays C#

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

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

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

例如:

数组1“ 1、2、3、4、6”

数组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

提前致谢

如果任一文本框中有多行,这将无法正常工作-有人能找出原因吗?

您应该自己进行问题诊断-我怀疑在循环之前的一个简单断点(通过检查数组)会立即发现问题。

我很确定问题是您应该在"\\r\\n"而不是'\\n'上进行分割-当前,除了最后一行以外,所有行的末尾都将以流氓\\r结尾,这会弄乱结果。

您可以使用Lines属性来代替使用Text属性然后拆分它:

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

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

textBox3.Lines = results.ToArray();

用力,卢克:

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

在定界符中添加了“ \\ r”。

您可以尝试以下代码(只需将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) });

产生:

在此处输入图片说明

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM