Print the first repeating character in String
August 7, 2012
Print array in the forward and backward direction recursively
August 8, 2012

Print all repeating characters in a string

We have already seen the problem to print first repeating character in a string. In this post we will be looking at printing all the repeating characters in the string. For example:

Input String: "www.ritambhara.in"         Output: w.ria
Input String: "social.ritambhara.in"      Output: ia.r
Input String: "meenakshi"                 Output: e 

Note that we are printing the repeating character only once.
Solution:
We will be extending the second method in the solution to printing the first repeating character in the string.

Step-1: Create the count array.
        which will hold the number of times a character is repeating in the string.
Step-2:
    For each element of the string
        If count is >1
            print the character
            negate the count (multiply by -1) //so that it doesn't get printed again

Code:

void printRepeating(char* str)
{
    // Boundary check
    if(str == NULL || str[0] == '')
    {
        printf("EMPTY STRING");
        return;
    }
    // Count Array. All elements are zeros
    int cntArr[256] = {0};
    // Populating the Count Array
    for(int i = 0; str[i] != '';  i++)
        cntArr[str[i]]++;
    // Getting the index of Maximum count in the Array
    int maxCntIdx = 0;
    for(int i=0; str[i] != '';  i++)
    {
        if(cntArr[str[i]] > 1)
        {
            printf(" %c ", str[i]);
            cntArr[str[i]] *= -1;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *