Software & Finance





C++ FAQ - How to count the unique number of ASCII characters in a given string?





The number of  ASCII characters are 255. If we can have a 255 counter variables in an array, then we can solve this problem.

The following are the 3 steps:

1. Initialize the 255 counter variables in the array.
2. Iterate through the for loop for the given string and increment counter value at the respective position.
3. Display the character and the occurrence at the end.


Source Code


 

#include <stdio.h>

#include <iostream>

#include <tchar.h>

 

// count the unique number of ASCII characters

 

int _tmain(int argc, _TCHAR* argv[])

{

    int count[255];

    char input[1024];

    std::cout << "Enter a Line (Max 1024 characters, Press <Enter> when you are done):";

 

    int j = 0;

    while(1)

    {

        int ch = getchar();

        if( ch == 10)

            break;

        input[j++] = ch;

        if(j >= 1024)

            break;

    }

   

    for(int i = 0; i < 255; i++)

        count[i] = 0; // Assign the counter variable to Zero

 

    int len = strlen(input);

    for(int i = 0; i < len; i++)

        count[input[i]]++; // Add the counter for the corresponding ASCII character

 

    int uniqueCount = 0; 
for(int i = 0; i < 255; i++)

    {

        if( count[i] > 0)

        {

            std::cout << "\nCharacter: '" << (char) i;

            std::cout << "'\tOccurrence: " << count[i];

            uniqueCount++; // Holds the unique number of characters
}

    }

    std::cout << "\n";

 

    return 0;

}

Output


 

Enter a Line (Max 1024 characters, Press <Enter> when you are done):WELCOME TO www.softwareandfinance.com

 

Character: ' '  Occurrence: 2

Character: '.'  Occurrence: 2

Character: 'C'  Occurrence: 1

Character: 'E'  Occurrence: 2

Character: 'L'  Occurrence: 1

Character: 'M'  Occurrence: 1

Character: 'O'  Occurrence: 2

Character: 'T'  Occurrence: 1

Character: 'W'  Occurrence: 1

Character: 'a'  Occurrence: 3

Character: 'c'  Occurrence: 2

Character: 'd'  Occurrence: 1

Character: 'e'  Occurrence: 2

Character: 'f'  Occurrence: 2

Character: 'i'  Occurrence: 1

Character: 'm'  Occurrence: 1

Character: 'n'  Occurrence: 3

Character: 'o'  Occurrence: 2

Character: 'r'  Occurrence: 1

Character: 's'  Occurrence: 1

Character: 't'  Occurrence: 1

Character: 'w'  Occurrence: 4