String Frequency Count

code:
simple code:

#include<stdio.h>
int main()
{
    char str[300],ch;
    int i,frequency=0;
    printf("enter string:");
    gets(str);
    printf("enter character:");
    scanf("%c",&ch);

    for(i=0; str[i]!='\0'; i++)
    {
        if(ch==str[i])
        {
            frequency++;
        }

    }
    printf("%d",frequency);

    return 0;
}

good output:

#include<stdio.h>
#define MAX_SIZE 100
int main()
{
    char string[MAX_SIZE];
    int i,j,len;
    int frequency[26];
    gets(string);
    for(j=0;string[j]!='\0';j++);
   // printf("%d",i);
    for(i=0;i<26;i++)
    {
        frequency[i]=0;
    }

    for(i=0;i<j;i++)
    {
        if(string[i]>='a' && string[i]<='z'){
            frequency[string[i]-97]++;
        }
        else if(string[i]>='A' && string[i]<='Z'){
            frequency[string[i]-65]++;
        }
    }

    for(i=0;i<25;i++)
    {
        if(frequency[i]!=0){
            printf("%c(%d)\t",(i+97),frequency[i]);
        }
    }


    return 0;
}

Reference: http://www.codeforwin.in/2015/04/c-program-to-calculate-the-frequency-of-each-character-in-a-line.html

101cproblems.com solution:

#include<stdio.h>
int main()
{
    int i,length=0;
    char str[200],arr[200];
    gets(str);
    for(i=0; i<=122; i++)
    {
        arr[i]=0;
    }
    for(i=0; str[i]!='\0'; i++)
    {
        length++;
    }
    for(i=0; i<length; i++)
    {
        arr[str[i]]++;
    }
    for(i=0; i<=122; i++)
    {
        if(arr[i]!=0)
        {
            printf("%c(%d)",i,arr[i]);
        }
    }
    return 0;
}

 

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

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