Find the number of Occurrences of character in a string

#include"stdio.h"

int main()
{
    char a[100],b;
    int i = 0,n = 0,len = 0;
    printf("Enter The String Of Characters : ");
    scanf("%s",a);
    printf("\n\nEnter The Character You want to Count : ");
    scanf("%c",&b);
    
    len = strlen(a);
    
    fflush(stdin);
    
    for(i = 0;i <= len;i++)
    {
          if(b == a[i])
          {
                  n++;        
          }      
    }
    
    printf("\n\nNumber Of Occurences of %c in %s is : %d",b,a,n);
    
    getch();
    return 0;   
}

And the question is ?

#include
#include
#include
using namespace std;
int count(const char * const str, char a);

int main()
{
char string[80];
char ch;
int i, count;

cout << "Enter a character: ";
cin >> ch;

cout << "Enter a string: ";
cin >> *string;

count(string, ch);
return 0;
}

int count(const char * const str, char a)
{

int counter = 0;

for (int i = 0; str[i] != ‘\0’; i++)
if (str[i] == a)
*counter++;
cout << "Number of occurrences of " << a << " in " << str << " = " << count << endl;
return counter;
}

@kpr07
You can use Hash array for this problem because string may have only 255 different type of character

#include<stdio.h>
#include<string.h>
int main()
{
    char st[100],c;

    int Hash[256] = {0};

    scanf("%s",st);

    fflush();

    scanf("%c",c);

    int l = strlen(st);

    for(i=0;i<l;i++)

    Hash[st[i]]++;

    printf("%d\n",Hash[c]); // this will give you the occurrence of  character in a string. 

    return 0;
}

If you have any doubt then you may ask me.

Happy Coding!!!

2 Likes