C Programming: Count of each character in a given string
33. Count Each Character Occurrence
Write a C program to count each character in a given string.
Sample Solution:
C Code:
#include<stdio.h>
#include<string.h>
// Function to check if a character exists in the array and count its occurrence
int if_char_exists(char c, char p[], int x, int y[]) {
	int i;
	for (i = 0; i <= x; i++) {
		if (p[i] == c) {
			y[i]++; // Increment count if character is found
			return (1); // Return 1 if character exists
		}
	}
	if (i > x) return (0); // Return 0 if character doesn't exist
}
int main() {
	char str1[80], chr[80]; // Declaring string arrays
	int n, i, x, ctr[80]; // Declaring variables for length, iteration, counts
	printf("Enter a string: ");
	scanf("%s", str1); // Inputting a string from the user
	n = strlen(str1); // Finding length of input string
	chr[0] = str1[0]; // Storing the first character of the input string in another array
	ctr[0] = 1; // Initializing the count of that character as 1
	x = 0; // Initializing index for the new array as 0
	for (i = 1; i < n; i++) {
		if (!if_char_exists(str1[i], chr, x, ctr)) { // If character doesn't exist in the new array
			x++; // Increment index for the new array
			chr[x] = str1[i]; // Add the new character to the new array
			ctr[x] = 1; // Initialize its count as 1
		}
	}
	printf("The count of each character in the string %s is \n", str1);
	for (i = 0; i <= x; i++) // Printing the count of each character
		printf("%c\t%d\n", chr[i], ctr[i]);
}
Output:
Enter a str1ing: The count of each character in the string w3resource is w 1 3 1 r 2 e 2 s 1 o 1 u 1 c 1
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to count the frequency of every character in a string using an array indexed by ASCII values.
 - Write a C program to build and display a frequency table for all characters present in a string.
 - Write a C program to count each character’s occurrences recursively and then print the counts in order.
 - Write a C program to iterate over a string and output each unique character along with its frequency.
 
Go to:
PREV : Find Repeated Character.
NEXT : Uppercase Vowels in String.
C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
