Reputation: 13
I'm pretty new to C# and still learning about arrays. I got a problem where I have to compare two strings, and what I have to compare is how many times the same letter is in the same place in both strings. I made a for loop and an if statement that I feel should work, but it doesn't add to the counter and I can't see the problem myself.
I've searched how to compare char arrays and i found that the for loop I have would probably be best for this problem, but after it stopped working I'm not sure what I should do. I've gone into the debugging mode on visual studio and looked at the values as the code runs, and everything seems fine up until the if statement, which I think is the source of the problem I have.
//counter for the answer: how many parking spaces shared
int counter = 0;
//int for the number of spaces
int num = 0;
//takes number from textbox into num
int.TryParse(txtNumber.Text, out num);
//parking spaces from first day
string yesterday = txtYesterday.Text;
//parking spaces from second day
string today = txtToday.Text;
//my idea was to put both days into char arrays and compare
each spot in a for loop
char[] y = yesterday.ToCharArray();
char[] t = today.ToCharArray();
for(int i = 0; i < num; i++)
{
//so if the first spot is the same as the first spot on the
other day, and the spot has the correct letter then it should work
if(y[i] == t[i] && y[i].Equals("C"))
{
counter++;
}
}
MessageBox.Show(counter.ToString());
an example input would be
3
.CC
..C
the answer should be 1, because one spot was occupied on both days.
Upvotes: 0
Views: 564
Reputation: 18155
Your problem lies in the following line
if(y[i] == t[i] && y[i].Equals("C"))
You are taking a character at time in your loop. So it needs to be compare with a character rather than string.
if(y[i] == t[i] && y[i].Equals('C'))
Upvotes: 1
Reputation: 7091
You have char array so you'll need to see if y[i].Equals("C")
by comparing chars not strings:
y[i].Equals('C')
Upvotes: 1