我想将字符串输入与char[] List.If进行比较--字符串中的字母等于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);发布于 2015-03-29 10:51:04
您跳过了List数组的第一个和最后一个字符,除此之外,您只比较I‘the输入字符和List数组中的I’the字符。您需要一个嵌套循环,以便将输入字符串的所有字符与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);发布于 2015-03-29 10:53:33
数组索引从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++;
} https://stackoverflow.com/questions/29328203
复制相似问题