我在编写一个接受字符串并计算第一个字符(或任何字符)出现次数的方法时遇到了问题。我写的代码在下面,但由于某种原因,当我运行它时,它总是返回正确计数的一半。任何帮助将不胜感激,谢谢。
public static void countOccurrences(String string1) {
int counter = 0;
char toCheck = string1.charAt(0);
char compareChar;
for (int i = 0; i < string1.length(); i++) {
compareChar = string1.charAt(i);
if (toCheck == compareChar) {
counter++;
}
i++;
}
System.out.println(toCheck + " appears " + counter + " times in string1.");
}
最佳答案
你在每次迭代中递增 i
两次,所以你跳过了一半的字符:
for (int i = 0; i < string1.length(); i++) { // i is incremented here
compareChar = string1.charAt(i);
if (toCheck == compareChar){
counter++ ;
}
i++ ; // i is incremented again here - remove this line
}
关于java - 计算字符串中的字符出现次数 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31728607/