c++stringchar

Check for unique characters in a string


I'm trying to write a code that checks to see if a string is made up of unique characters. I do some data validation in the first few lines, and inputting code with these conditions (length = 1 or length > 36) works. When I input a string that does not meet the previously stated requirements, I attempted to compare each char of my string with every other char. Even for strings of unique characters, like the one in the following example, it returns that the string is not made up of unique characters.

string string = "abcdefghijklmnopqrstuvwxyz0123456789";
bool uniqueCharacters = false;

//if length is 1, automatically return that the string is made up of unique characters
if (string.length() == 1) {
    uniqueCharacters = true;
}

 //there are 26 letters and 10 numbers, so if a string is made up of more than 36 chars, there must be some overlap
if (string.length() > 36) {
    uniqueCharacters = false;
}

else if (string.length() > 1 && string.length() < 37) {
    for (int i = 0; i < string.length(); i++) {
        for (int j = 1; j < string.length(); j++) {
            if (string[i] == string[j]) {
                uniqueCharacters = false;
            }
            else {uniqueCharacters = true;}
        }
    }
}

if (uniqueCharacters == true) {
    cout << "This string contains all unique characters \n";
}
if (uniqueCharacters == false) {
    cout << "This string does not contain all unique characters \n";
}

I assume this is a logic error, but I cannot figure it out. Any ideas?


Solution

  • string string = "abcdefghijklmnopqrstuvwxyz0123456789";
    bool uniqueCharacters = false;
    
    //if length is 1, automatically return that the string is made up of unique characters
    if (string.length() == 1) {
        uniqueCharacters = true;
    }
    
     //there are 26 letters and 10 numbers, so if a string is made up of more than 36 chars, there must be some overlap
    if (string.length() > 36) {
        uniqueCharacters = false;
    }
    
    else if (string.length() > 1 && string.length() < 37) {
        for (int i = 0; i < string.length(); i++) {
            for (int j = i+1; j < string.length(); j++) {
                if (string[i] == string[j]) {
                    uniqueCharacters = false;
                }
                else {uniqueCharacters = true;}
            }
        }
    }
    
    if (uniqueCharacters == true) {
        cout << "This string contains all unique characters \n";
    }
    if (uniqueCharacters == false) {
        cout << "This string does not contain all unique characters \n";
    }