how to find number of occurrences of a character in c with pointers code example
Example 1: find character from string c count
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000],c;
int i,count=0;
printf("Enter the string : ");
gets(s);
printf("Enter character to be searched: ");
c=getchar();
for(i=0;s[i];i++)
{
if(s[i]==c)
{
count++;
}
}
printf("character '%c' occurs %d times \n ",c,count);
return 0;
}
Example 2: how to count the most common letter in a string c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ENG_LETTERS 26
#define STR_LEN 100
int main()
{
int countArray[ENG_LETTERS] = {0};
char str[STR_LEN] = { 0 };
char engChar = 'a' - 1;
int length = 0;
int i , j = 0;
int max = 0;
int index = 0;
printf("Please enter a string:\n");
fgets(str , STR_LEN , stdin);
length = strlen(str);
for(i = 0 ; i <= length;i++)
{
if(str[i] == '\n')
{
str[i] = '\0';
}
}
for(i = 0;i < ENG_LETTERS;i++)
{
engChar++;
for(j = 0;j <= length - 1;j++)
{
if(str[j] == engChar)
{
countArray[i]++;
}
}
}
engChar = 'a'- 1;
for(i = 0; i <= ENG_LETTERS - 1;i++)
{
engChar++;
printf("There are %d %c letters\n", countArray[i],engChar);
}
system("PAUSE");
return 0;
}