Reputation: 11
public static void countLetters (String s, char x){
int length = s.length();
int count = 0;
int index = 0;
int z = 0;
while (index < length) {
int y = s.indexOf(x, z);
z = z+1;
if(s.charAt(y)==x){
count = count + 1;
}
index = index + 1;
}
System.out.println(count);
Hello everyone, I am a newbie with java so any little guidance would be greatly appreciated. I am trying to write a method to count letter occurrence in a given string and a char.
The current method does count but not quite there. I am asked to use indexOf method to solve this problem. Problem i am having is if I put a text "amazing" and asked to find char 'a' it goes through first 'a' and count updates but then when it comes to char 'm' count again updates which I don't want it.
I am using a book called think java by Allen Downey - Exercise 8.3. Its not any homework :).
Upvotes: 0
Views: 3048
Reputation: 846
You should use this :
int length = s.length();
int count = 0;
int z = 0;
while (z < length) {
int y = s.indexOf(x, z);
if(y == -1){
break;
}
z = (y == z) ? z + 1 : y + 1;
if (s.charAt(y) == x) {
count = count + 1;
}
}
System.out.print(count);
basically when you use the s.indexOf(chr, fromIndex)
it checks for the char from the specified index until it locates it that's why when it is at m
it still checks till it finds a
in the string. Also you should check for a -1
if the string is not found and break as that will be the end of the search since the string is not found from the index to the end of the string. This prevents indexOfBoundsException when doing the check if(s.charAt(y) == x)
The expression z = (y == z) ? z + 1 : y + 1;
is more like an if else statement. the ?
is a ternary operator and is a short form of:
if(y == z){
z = z + 1;
}else{
z = y + 1;
}
since it's a simple if an else statement that sets the value of a variable with an expression the ternary operator could be used to save lines of code.
Upvotes: 1
Reputation: 3370
You are iterating over the string one char at a time: z = z+1
, but when you call s.indexOf(x, z)
, first occurrence of x
(greater than z
) is returned. So you iteration is going to go like following :
So instead of z = z+1
, you should be doing z = y+1
, and stop iterating once s.indexOf(x, z)
return -1.
Upvotes: 0
Reputation: 2200
This way
public static void countLetters(String string, char character) {
int count = 0;
int index = 0;
while(true) {
index = string.indexOf(character, index) + 1; // +1 is to continue search
if (index == 0) //from next character after match
break;
count++;
}
System.out.println(count);
}
Calling it with countLetters("amazingaa", 'a');
gives 4
Upvotes: 0