简体   繁体   English

Java:使用charAt比较char Array的输入

[英]Java:compare an input to a char Array using charAt

I would like to compare String input to the char[] List.If a letter inside the string is equal to the char[] List, the count should iterate but it always prints out 0. Thanks! 我想将输入的字符串与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);

Array index starts from 0 and goes upto n-1, So your loop should be: 数组索引从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 you need to compare an element within the input with any of characters in list then you could do something like: 如果您需要将输入中的元素与列表中的任何字符进行比较,则可以执行以下操作:

 if (input.indexOf(List[i], 0) >= 0) {
     count++;
 }    

You are skipping the first and last characters of the List array, and beside that, you only compare the i'th input character to the i'th character in your List array. 您将跳过List数组的第一个和最后一个字符,除此之外,您仅将第i个输入字符与List数组中的第i个字符进行比较。 You need a nested loop in order to compare all the characters of the input String to all the characters of the List array. 您需要嵌套循环才能将输入String的所有字符与List数组的所有字符进行比较。

char[] List={'a','b','c','d'};

int count=0;
for(int i=0;i<List.length;i++){
    for (int j=0;j<input.length();j++) {
        if(input.charAt(j)==List[i]){
            count++;
        }
    }
}
System.out.println(count);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM