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:
- 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.
- Declare a string variable to hold the input string:
std::string inputString;
- 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.
- Create a
std::set
to store unique characters:
std::set<char> uniqueChars;
The std::set
container stores unique elements in sorted order.
- 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.
- 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.