我试图在返回 true 之前检查字符串输入是否包含至少一个数字和一个字母。
我的方法是首先循环遍历单词。
如果单词不包含 isalpha
或 isdigit
,则返回 false。
检查之后,我创建了两个计数(一个用于数字,一个用于字母)。我检查是否 isalpha
然后将计数加一。然后我检查 isdigit
并添加到该计数。
最后我检查两个计数是否大于或等于 1(意味着它至少包含一位数字和一个字母)并返回 true。我知道计数不是最好的方法,但我只是想测试该方法,但它不起作用,我不确定我的逻辑哪里错了。
bool isDigitLetter::filter(string word) {
int digit = 0;
int letter = 0;
if(word.empty()) {
return false;
}
for(int i = 0; i < word.length(); i++) {
if(!isalpha((unsigned char)word[i]) || !isdigit((unsigned char)word[i])) {
return false;
}
}
for(int x = 0; x < word.length(); x++) {
if(isalpha((unsigned char)word[x])) {
letter+=1;
}
if(isdigit((unsigned char)word[x])) {
digit+=1;
}
}
if(digit && letter>= 1) {
return true;
}
}
我在想也许可以使用 isalnum
但如果它包含任何一个但不检查它是否包含至少一个则返回 true。
最佳答案
bool isDigitLetter::filter(string word) {
bool hasLetter = false;
bool hasDigit = false;
for (int i = 0; i < word.size(); i++) {
if (isdigit(word.at(i))) { hasDigit = true; }
if (isalpha(word.at(i))) { hasLetter = true; }
}
return (hasLetter && hasDigit);
}
此解决方案删除了大量不必要的代码。
基本上,它遍历字符串并检查每个字符是字母还是数字。每次它看到一个,它都会更新 hasLetter/hasDigit 变量。如果两者都为真则返回真,否则返回假。
编辑:这个解决方案更快——如果它已经看到一个字母和一个数字,它会立即返回。
bool isDigitLetter::filter(string word) {
bool hasLetter = false;
bool hasDigit = false;
for (int i = 0; i < word.size(); i++) {
if (isdigit(word.at(i))) { hasDigit = true; }
if (isalpha(word.at(i))) { hasLetter = true; }
if (hasDigit && hasLetter) { return true; }
}
// we got here and couldn't find a letter and a digit
return false;
}
关于C++ 检查字符串是否包含至少 1 个数字和 1 个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48098173/