Find the different characters present in a string

后端 未结 3 1524
粉色の甜心
粉色の甜心 2021-01-20 22:07

Is there any way to find the all the unique characters present in a string without finding all the occurrences of the string ? For example, Let it be s

相关标签:
3条回答
  • 2021-01-20 22:49

    You can do that using std::sort, std::unique, std::string::erase

    Note : original string will be modified [If you don't want that make a copy of it]

    std::string str = "mississippi";
    std::sort(std::begin(str), std::end(str));
    auto last = std::unique(std::begin(str), std::end(str));
    str.erase(last, std::end(str));
    
    0 讨论(0)
  • 2021-01-20 23:06

    Make a set of characters and put all items from string to it, then you will have set with "alphabet" of your string.

    E.g.:

    #include <string>
    #include <iostream>
    #include <set>
    
    int main(void)
    {
        std::string a = "mississippi";
        std::set<char> alphabet;
        alphabet.insert(a.begin(), a.end());
        std::cout << "Set of chars has " << alphabet.size() << " items." << std::endl;
        for (auto a : alphabet)
        {
            std::cout << a << std::endl;
        }
    }
    

    Original string is not modified in that example and there is no need to pre-sort.

    0 讨论(0)
  • 2021-01-20 23:09

    Sounds uncommon enough that it's not part of the STL.
    I'd simply try iterating through the string and creating / incrementing the count of numbers in a Hashset. Then, grab all the Keys to determine unique values. Good Luck

    0 讨论(0)
提交回复
热议问题