简体   繁体   中英

How to count consecutive times a character appears in a String

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM