我正在尝试编写一段代码,用于检查字符串是否由唯一字符组成。在前几行进行了一些数据验证,并且输入符合这些条件的代码(长度=1或长度>36)是有效的。当我输入不符合先前规定要求的字符串时,我尝试将我的字符串的每个字符与其他每个字符进行比较。即使对于像以下示例中的唯一字符串一样的唯一字符的字符串,它也会返回该字符串不是由唯一字符组成的。
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";
}
我认为这是一个逻辑错误,但是我无法找出问题所在。有什么想法吗?
int j = 1
应该改为int j = i + 1
。 - Jarod42