首页 > 解决方案 > 如何修复此 for 循环以比较两个 char 数组?

问题描述

我对 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,因为这两天都有一个位置被占用。

标签: c#

解决方案


你有 char 数组,所以你需要y[i].Equals("C")通过比较字符而不是字符串来查看:

y[i].Equals('C')

推荐阅读