Ads by ProfitSence
Close

C Program Displaying the count of each character in a string

Last Updated on Wednesday 5th Oct 2022

Frequency of Characters in a string in c

C Program Displaying the count of each character in a string.

Create a string called str. The last element in the string will be a null character. Define another string called chr of matching length to store the characters of str.

			
					#include<stdio.h>

#include<string.h>
int exists(char u, char p[], int v, int q[]) {
  int i;
  for (i = 0; i <= v; i++) {
    if (p[i] == u) {
      q[i]++;
      return (1);
    }
  }
  if (i > v) return (0);
}
void main() {
  char str[80], chr[80];
  int n, i, x, count[80];
  printf("Enter a string: ");
  scanf("%s", str);
  n = strlen(str);
  chr[0] = str[0];
  count[0] = 1;
  x = 0;
  for (i = 1; i < n; i++) {
    if (!exists(str[i], chr, x, count)) {
      x++;
      chr[x] = str[i];
      count[x] = 1;
    }
  }
  printf("The count of each character in the string %s is \n", str);
  for (i = 0; i <= x; i++)
    printf("%c\t%d\n", chr[i], count[i]);
}

			
	
  • Each of the characters will be assigned to the respective index locations of str, that is, r will be assigned to index location str[0], a will be assigned to str[1], and so on.
  • Using the strlen function, we will first compute the length of the string.
  • When the for loop completes, all of the characters in the string are accessed.
  • The chr array will have individual characters of the string, and the count array will have the count, or the number of times the characters represented by the chr array have occurred in the string.
			
					Enter a string: abcdabcaba
The count of each character in the string abcdabcaba is 
a   4
b   3
c   2
d   1