w3resource

C Programming: Count of each character in a given string

C String: Exercise-33 with Solution

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]);
}

Sample 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 :

Flowchart: Count of each character in a given string

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Write a C programming to find the repeated character in a given string.
Next: Write a C programming to convert vowels into upper case character in a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming-exercises/string/c-string-exercise-33.php