I am a java beginner and want to do some logic stuffs. I have started with a simple program (i.e) to find the total number of occurrences of a character in a string. But i ended up with this exception
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 52
at java.lang.String.charAt(Unknown Source)
And i used the following code
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);
}
}
Copyright Notice:Content Author:「raduns」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18341252/java-exception-in-counting-number-of-occurrences-of-character-in-a-string