c# - 如何修复此 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,因为这两天都有一个位置被占用。
解决方案
你有 char 数组,所以你需要y[i].Equals("C")
通过比较字符而不是字符串来查看:
y[i].Equals('C')
推荐阅读
- javascript - 如何使用 javascript 对象在属性中使用悬停?
- python-3.x - 从分组的数据框中选择前 n 个最大的组
- generics - Difference between using a generic type and using its upper bound type directly as the parameter type in a function
- python - 如何在python中使用循环读取/计算数据?
- amazon-web-services - 更改了我的云形成 IAM 组名称,但旧的 IAM 组不会被删除
- java - 如何解决这种非法的表达开头?
- angular - 我可以将单个 EntityAdapter 用于同一 EntityState 的几个实例吗?
- python - 如何使用 flask.redirect 发送 POST 请求?
- c++ - 基于范围的自定义迭代器:常量问题
- mysql - 可以将另一个表作为表中的一行引用吗?