我对C#还是很陌生,仍然在学习数组。我遇到一个问题,我必须比较两个字符串,而我必须比较的是两个字符串中相同字母在同一位置的次数。我做了一个for循环和一个if语句,觉得可以使用,但是它没有添加到计数器中,而且我自己也看不到问题。
我已经搜索了如何比较char数组,并且发现for循环可能是解决此问题的最佳方法,但是在停止工作后,我不确定应该怎么做。我进入了Visual Studio的调试模式,并在代码运行时查看了这些值,直到if语句(我认为这是我遇到的问题的根源)之前,一切似乎都很好。
//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());
输入示例
3
.CC
.. C
答案应该为1,因为这两天都占用了一个地点。
答案 0 :(得分:1)
您有char数组,因此您需要通过比较char而不是字符串来查看y[i].Equals("C")
是否为>
y[i].Equals('C')
答案 1 :(得分:1)
您的问题出在以下几行
if(y[i] == t[i] && y[i].Equals("C"))
您正在循环中选择一个角色。因此,需要将其与字符而不是字符串进行比较。
if(y[i] == t[i] && y[i].Equals('C'))