我想将字符串输入与 char[] 列表进行比较。如果字符串内的字母等于 char[] 列表,则计数应该迭代,但它总是打印出 0。谢谢!
char[] List={'a','b','c','d'};
int count=0;
for(int i=1;i<List.length-1;i++){
if(input.charAt(i)==List[i]){
count++;
}
}
System.out.println(count);
最佳答案
数组索引从 0 开始一直到 n-1,所以你的循环应该是:
for(int i=0;i<List.length;i++){
if(input.charAt(i)==List[i]){//assuming you have same number of characters in input as well as List and you want to compare ith element of input with ith element of List
count++;
}
}
如果您需要将输入中的元素与列表中的任何字符进行比较,那么您可以执行以下操作:
if (input.indexOf(List[i], 0) >= 0) {
count++;
}
关于Java:使用 charAt 将输入与 char 数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29328203/