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?
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).
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 .
We can convert a char to a string object in java by using the Character. toString() method.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With