Im trying to write a simple program that will take 2 multi line inputs from 2 textboxes, put them in 2 arrays and compare them.
I want to check if an entry in array 1 (each line of textbox 1 is a separate entry in array 1) is in array 2 (each line of text box 2 is a separate entry in array 2).
then output the results to a textbox.
for example:
Array 1 “one, two, three, four, six”
Array 2 “one, three, five, four”
it should output:
one = found
two = not found
three = found
four = found
six = not found
The code i have so far is as follows:
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";
}
}
}
This is not working correctly if there is more than one line in the either textbox – i cant figure out why.. the following is happening in test runs:
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
Thanks in advance
You should work on diagnosing problems yourself – I suspect that a simple breakpoint just before the loop, following by examining the arrays, would find the issue immediately.
I’m pretty sure the problem is just that you should be splitting on
"\r\n"instead of'\n'– currently you’ll end up with a rogue\rat the end of all lines other than the last one, which will mess up the results.Rather than using the
Textproperty and then splitting it, you could just use theLinesproperty instead:EDIT: As noted in Guffa’s answer, you will also want to avoid replacing
textBox3.Texton each iteration. Personally I’d probably use create aList<string>, add to it on each iteration, then at the end use: