finding no of unique characters in a string c++

To find the number of unique characters in a string in C++, you can use a combination of a std::set and string iteration. Here is the step-by-step explanation:

  1. Include the necessary header files:
#include <iostream>
#include <set>

These header files are needed to use the std::set container and the standard input/output stream.

  1. Declare a string variable to hold the input string:
std::string inputString;
  1. Read the input string from the user:
std::cout << "Enter a string: ";
std::cin >> inputString;

This code prompts the user to enter a string and reads it into the inputString variable.

  1. Create a std::set to store unique characters:
std::set<char> uniqueChars;

The std::set container stores unique elements in sorted order.

  1. Iterate over each character of the string:
for (char c : inputString) {
    uniqueChars.insert(c);
}

This loop iterates over each character in the inputString and inserts it into the uniqueChars set. Since set elements are unique, only unique characters will be stored in the set.

  1. Print the number of unique characters:
std::cout << "Number of unique characters: " << uniqueChars.size() << std::endl;

The size() function returns the number of elements in the uniqueChars set, which gives us the count of unique characters in the string.

Here is the complete code:

#include <iostream>
#include <set>

int main() {
    std::string inputString;
    std::cout << "Enter a string: ";
    std::cin >> inputString;

    std::set<char> uniqueChars;
    for (char c : inputString) {
        uniqueChars.insert(c);
    }

    std::cout << "Number of unique characters: " << uniqueChars.size() << std::endl;

    return 0;
}

This code will calculate and display the number of unique characters in the input string.