Search code examples
c++stringstdset

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


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?


Solution

  • 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