Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a std::set of characters in a string, as strings?

Tags:

c++

string

stdset

I have a std::string. I want the set of unique characters in it, with each character represented as a std::string.

I can get the set of characters easily:

std::string some_string = ...
std::set<char> char_set(some_string.begin(), some_string.end());

And I could convert them to strings like this:

std::set<std::string> string_set;
for (char c: char_set) {
    string_set.emplace(1, c);
}

But such an approach seems awkward. Is there a better (preferrably standard-library one-liner) way to do this?

like image 780
EMBLEM Avatar asked Apr 21 '15 18:04

EMBLEM


People also ask

How do I get all the letters in a string in C++?

string at() in C++std::string::at can be used to extract characters by characters from a given string. Syntax 2: const char& string::at (size_type idx) const idx : index number Both forms return the character that has the index idx (the first character has index 0).

Is std::string the same as string?

There is no functionality difference between string and std::string because they're the same type. That said, there are times where you would prefer std::string over string .

Can you convert char to string?

We can convert a char to a string object in java by using the Character. toString() method.

What does std::string () do?

The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.


1 Answers

You can use:

std::for_each(some_string.begin(), some_string.end(),
              [&string_set] (char c) -> void { string_set.insert(std::string({c}));});

You can also use:

   for (char c: some_string)
   {
      string_set.insert(std::string{c});
   }

Working program:

#include <iostream>
#include <string>
#include <set>
#include <algorithm>

int main()
{
   std::string some_string = "I want the set of unique characters in it";
   std::set<std::string> string_set;
   for (char c: some_string)
   {
      string_set.insert(std::string{c});
   }

   for (std::string const& s: string_set)
   {
      std::cout << s << std::endl;
   }
}

Output:


I
a
c
e
f
h
i
n
o
q
r
s
t
u
w
like image 117
R Sahu Avatar answered Sep 20 '22 22:09

R Sahu