简体   繁体   中英

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[] 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:

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. You need a nested loop in order to compare all the characters of the input String to all the characters of the List array.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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