write a program to count how many times character is repeated in a given string

20 Sep 2022 Balmiki Mandal 0 C Programming

A C program to count how many times each character is repeated in a given string involves iterating through the characters in the string, counting the number of occurrences of each character, and then displaying the results. Here is an example program

c program to count how many times character is repeated in a given string

#include
int main()
{
    char s[20],ch;
    int i,j,f=0,c;
    printf("Enter the string:");
    scanf("%s",s);
    for(i=0;s[i];i++)
    {
        ch=s[i];
        if(i!=0)
        {
            for(j=i-1,f=0;j>=0;j--)
            if(s[j]==ch)
            {
                f=1;
                break;
            }
        }
        if(f==0 || i==0)
        {
            for(j=j+1,c=0;s[j];j++)
            if(s[j]==ch)
            c++;
            printf("%c repeated %d Times\n",ch,c);
        }
    }
}

Output:

Enter the string: abcacbad

a repeated 3 Times

b repeated 2 Times

c repeated 2 Times

d repeated 1 Time

 

C program to count how many times character is repeated in a given string

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    int count[256] = {0}; // initialize the count array to zero
    int i, len;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    len = strlen(str);

    for (i = 0; i < len; i++) {
        count[str[i]]++; // increment the count of the current character
    }

    printf("Character frequency in '%s':\n", str);
    for (i = 0; i < 256; i++) {
        if (count[i] > 0) {
            printf("%c: %d\n", i, count[i]);
        }
    }

    return 0;
}

In this program, we first declare an array str of size 100 to store the input string, an array count of size 256 to store the frequency count of each character (one for each ASCII character), and variables i and len.

We then use fgets function to read a line of input from the user and store it in str.

Next, we use a for loop to iterate through the string str character by character. For each character, we increment the count of the corresponding ASCII value in the count array by 1.

Finally, we use another for loop to iterate through the count array and print the frequency count of each character that appears at least once.

Note: This program assumes that the input string contains no more than 99 characters, since we declare the str array with a size of 100 (one character is reserved for the null terminator). If you want to handle longer strings, you will need to adjust the array size accordingly.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.