[英]How to fix this for loop to compare two char arrays?
我是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,因為這兩天都占用了一個地點。
您有char數組,因此需要通過比較chars不是字符串來查看y[i].Equals("C")
:
y[i].Equals('C')
您的問題在於以下幾行
if(y[i] == t[i] && y[i].Equals("C"))
您正在循環中的某個時間拍攝人物。 因此,需要將其與字符而不是字符串進行比較。
if(y[i] == t[i] && y[i].Equals('C'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.