Prerequisites:
A string is a collection of characters and if we are converting it into a set the only reason can be to check the characters being used without duplicate values.
Example:
string s=”Geeks for Geeks is for Geeks”
// G e k s f o r i are characters
// set can store these characters in sorted order.
So, to Perform this operation there are two methods :
- Passing the string into the set constructor.
- Iterating the string using for loop.
1. Passing the string into the set constructor
Using predefined properties can really be useful while converting strings into sets. We can just insert elements by putting a range of string elements inside the constructor for copying elements inside the set.
Syntax:
set <char>set_obj ( begin( string_name ) , end( string_name ) )
Code:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string name = "geeksforgeeks";
set<char> my_name(name.begin(), name.end());
for (auto it : my_name) {
cout << it << " ";
}
cout << endl;
return 0;
}
|
Here the string ‘name’ is passed in the set constructor. And the characters in the string are converted into the set and then the elements are printed. Here the elements are printed in ascending order and there is no repetition of the elements(unique elements are printed).
2. Iterating the string using for loop
The simplest way to perform the task is using for loop. First, we can iterate over the string using loops by which we can directly insert elements inside the set.
Code:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string name = "jayadeep";
set<char> s1;
for (int x = 0; x < name.size(); x++) {
s1.insert(name[x]);
}
set<char>::iterator itr;
for (itr = s1.begin(); itr != s1.end(); itr++) {
cout << *itr;
}
cout << endl;
}
|
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
07 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...