Duplicated Letters – Solution

The challenge for this month’s Exercise is to write code that counts repeating letters in a string. For example, the string “Hello, this is a test” repeats the letters T and S three times, letters E, H, I, and L twice, and the letters A and O appear only once.

For my solution, I created two arrays, char input[] and int alphabet[]:

    char input[64],alphabet[26];

The input[] array holds the string input and alphabet[] keeps track of the letters that repeat. It’s initialized to all zeros, which represent false values for each letter of the alphabet:

/* initialize alphabet array */
for(x=0;x<26;x++)
    alphabet[x] = 0;

After text is input, a while loop scans each character in the input[] array, the string input:

x=max=0;
while(input[x])
{
    ch = input[x];
    /* skip non-alphabet characters */
    if(isalpha(ch))
    {
        /* increment character count */
        alphabet[toupper(ch)-'A']++;
        /* track largest count value */
        if( alphabet[toupper(ch)-'A'] > max )
            max = alphabet[toupper(ch)-'A'];
    }
    x++;
}

The char variable ch grabs a character from the input[] array; int variable x as an index. The isalpha(ch) test culls out only letters of the alphabet. When a letter is found, it’s offset within the index is incremented: alphabet[toupper(ch)-'A']++.

Variable max tracks the maximum number of letters repeated. So if U appears 6 times, max holds the value six. Where max is used is in a nested for loop structure that follows:

/* process results */
if(max>1)
{
    for(x=max;x>0;x--)
    {
        printf("Letter count %d:",x);
        for(y=0;y<26;y++)
            if(alphabet[y]==x)
                printf(" %c",y+'A');
        putchar('\n');
    }
}
else
{
    puts("String is unique: No two letters repeat.");
}

When max isn’t greater than 1, the if test fails and it’s assumed that no two letters repeat. Otherwise, the outer for loop scans each letter count value from max down to 1. The inner loop displays the repeated characters.

Here’s sample output:

Enter text: Unique words
Letter count 2: U
Letter count 1: D E I N O Q R S W

And:

Enter text: Ugly Ed is an ox
String is unique: No two letters repeat.

And:

Enter text: My solution is nothing fancy.
Letter count 4: N
Letter count 3: I O
Letter count 2: S T Y
Letter count 1: A C F G H L M U

Click here to view the full code for my solution. I also wrote a simpler version of this solution, one that displays repeated letters as they’re encountered. You can view this solution here.

I hope that you’ve devised some interesting solutions to the problem. Remember, no one perfect solution exists in C.

Leave a Reply