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 130 views
1 answer 145 views
1 answer 137 views
1 answer 161 views
1 answer 128 views
...