我是一个java初学者,想做一些逻辑的东西。我从一个简单的程序开始(即)来查找字符串中某个字符的出现总数。但我最终得到了这个例外
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 52
at java.lang.String.charAt(Unknown Source)
我使用了以下代码
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String myStr = "sofdaasdasdaofsdwerwtytuoftyutyusdfsdfsdcsadaswdeasd";
// Counting number of occurences of 'of' in myStr
int counter = 0;
int totalLength = myStr.length();
char char1;
char char2;
// To find of
String myVal = "of";
String cmpVal1;
String cmpVal2;
String cmpValStr;
for (int i = 0; i < totalLength; i++) {
char1 = myStr.charAt(i);
cmpVal1 = Character.toString(char1);
char2 = myStr.charAt(i + 1);
cmpVal2 = Character.toString(char2);
cmpValStr = cmpVal1 + cmpVal2;
if (cmpValStr == myVal) {
counter++;
}
}
System.out.print(counter);
}
}