C Program to count the number of unique characters in a string

Write a program to count the number of distinct characters in a string in C/C++.



Before we move further, we should know that there is a total of 128 characters in C/C++. Each character is represented by a unique integer value in the range [0, 127]. This numeric value is also known as the ASCII value of the character.


  • Let str[] be the input string.
  • Initialize an array hash[] of size 128. Fill the array with all zeros.
  • Perform the following operation for each character of str[]
    1. Let x be the current character of str[]
    2. Set hash[x] = 1
  • Count the number of 1’s in hash[]. Let it be C.
  • C is the final answer, the number of unique characters in the string.

// function to return the number of unique
// characters in str[]
int count_unique_char(char* str) {

	int hash[128] = { 0 };
	int i, c = 0;

	// reading each character of str[]
	for (i = 0; i < strlen(str); ++i) {
		// set the position corresponding 
		// to the ASCII value of str[i] in hash[] to 1
		hash[str[i]] = 1;

	// counting number of unique characters
	// repeated elements are only counted once
	for (i = 0; i < 128; ++i) {
		c += hash[i];

	return c;


int main() {

	char str[300];

	printf("Enter String: ");

	printf("Number of Unique Characters in String: %d", count_unique_char(str));



Enter String: Happiness
Number of Unique Characters in String: 7


Leave a Comment

Your email address will not be published. Required fields are marked *