I have the code
public static int count(String text, char letter)
{
int amount = 0;
for(int i = 0; i < text.length(); i )
{
if(text.charAt(i) == letter)
amount ;
}
return amount;
}
to count how many times a certain letter appears in a String (ex: eeeeee
has 6 e
's).
But how would I go about returning the number of times a character appears consecutively with only one String parameter?
For example:
AAbcde
would return1
(onea
after the firsta
)abcde
would return0
(no consecutive count)abccd
would return1
(onec
after the firstc
)aabccc
would return3
(onea
after the firsta
twoc
's after the firstc
)
Is there any simple way to achieve this similar to the code I already have?
CodePudding user response:
You can try next code
public static int count(String text)
{
int amount = 0;
for(int i = 1; i < text.length(); i )
{
if(text.charAt(i) == text.charAt(i-1))
amount ;
}
return amount;
}