简体   繁体   中英

How do I count how many double letters are in a string?

Double Letters: A letter that appears consecutively twice. (Ex: "Google", "programming buddy")

Google contains 1 double letter. Programming buddy contains 2 double letters in the string.

Anyways here's my code

int doubleLetters = 0;
for (int i = 0; i < characters.Length - 1; i++)
{
    if (characters[i] == characters[i + 1])
    {
        doubleLetters++;
    }
}

The problem here is if a string was spelled "Gooogle" (3 O's), it would return me a count of 2 instead of 1. Basically, it would return me how many conesective letters - 1 as the result.

How do I make it so it would count the right amount of double letters? So if the string is "looooool", it should give a 3. However, my code is counting this as 5 instead.

I'm trying to find code that can fix this.

    if (characters[i] == characters[i + 1])
    {
        doubleLetters++;
        i++;
    }

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