In this C++ tutorial, you shall learn how to get and print the unique characters of a given string using Set collection, with example programs.
Print Unique Characters of a String
To print unique characters of a string in C++, iterate over the characters of the string, insert each of the character in a set, and print them.
C++ Program
In the following program, we include set
library so that we can use Set collection. We take a string in str
variable, and print the unique characters in this string to console.
main.cpp
</>
Copy
#include <iostream>
#include <set>
using namespace std;
int main() {
string str = "apple";
set<char> uniqueChars;
//insert characters in set
for(char& ch : str) {
uniqueChars.insert(ch);
}
//print unique characters
for(auto ch : uniqueChars) {
cout << ch << endl;
}
}
Output
a
e
l
p
Reference
In the above program(s), we have used the following C++ concepts. The links have been provided for reference.
Conclusion
In this C++ Tutorial, we learned how to print unique characters of a given string.