Open In App

Converting String into Set in C++ STL

Last Updated : 07 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 :

  1. Passing the string into the set constructor.
  2. 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++




// C++ Program to Convert
// String to set
// Using set constructor
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    // Declaring the string
    string name = "geeksforgeeks";
 
    // declaring the string
    // and passing the string
    // in the set constructor
    set<char> my_name(name.begin(), name.end());
 
    // printing the set
    for (auto it : my_name) {
        cout << it << " ";
    }
    cout << endl;
   
  return 0;
}


Output

e f g k o r s 

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++




// C++ Program to Convert
// String into set
// Using for loop
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    // Declaring the string
    string name = "jayadeep";
 
    // Declaring the set
    set<char> s1;
 
    // inserting the string elements
    // into the set.
    for (int x = 0; x < name.size(); x++) {
        s1.insert(name[x]);
    }
    set<char>::iterator itr;
 
    // printing the set.
    for (itr = s1.begin(); itr != s1.end(); itr++) {
        cout << *itr;
    }
    cout << endl;
}


Output

adejpy


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads