How to determine if a string has all unique characters in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm>

bool all_unique_chars(std::string str) {
    sort(str.begin(), str.end());
    
    int size = str.length();
    
    for (int i = 0; i < size - 1; i++) {
        if (str[i] == str[i + 1]) {
            return false;
        }
    }
    return true;
}

int main() {
    std::string s = "c++ programming";
    all_unique_chars(s) == 1 ? std::cout << "True" : std::cout << "False";
    std::cout << "\n";
    
    s = "abcd";
    all_unique_chars(s) == 1 ? std::cout << "True" : std::cout << "False";
}




/*
run:

False
True

*/

 



answered May 5, 2022 by avibootz

Related questions

1 answer 120 views
1 answer 131 views
1 answer 127 views
1 answer 148 views
1 answer 119 views
...