Home > front end >  How to count consecutive times a character appears in a String
How to count consecutive times a character appears in a String

Time:09-23

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 return 1 (one a after the first a)
  • abcde would return 0 (no consecutive count)
  • abccd would return 1 (one c after the first c)
  • aabccc would return 3 (one a after the first a two c's after the first c)

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;
}
  •  Tags:  
  • java
  • Related