C++ 检查字符串是否至少包含 1 位数字和 1 个字母
C++ Check if String contains atleast 1 digit and 1 letter
我正在尝试在返回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变量。然后,如果两者都为真,则返回 true,否则返回 false。
编辑:此解决方案更快 - 如果它已经看到一个字母和一个数字,它会立即返回。
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;
}
它应该是这样的:
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;
}
}
return ((digit > 0) && (letter > 0));
}
您的问题出在以下行上:
if(digit && letter>= 1)
将其更改为:
if(digit >=1 && letter>= 1)
相关文章:
- 如何从也包含C++字母的文本文件中提取某些数字?
- 如何确定integer_sequence在编译时是否包含给定的数字?
- 如何生成仅包含 0 和 9 的数字
- 如何将较大数字中从0到9的单个数字放入只包含数字的数组中
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 正则表达式,包含名称 + "string" + 数字,没有其他内容
- 如何识别字符串只包含数字
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- 如何对包含数字和符号的字符串进行排序?
- 查看数字是否包含在未排序的双数字间隔内的最有效方法?
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何允许我的程序成功读取数字包含的文件
- 如何在包含数字的.bmp(二进制图像)中执行组件标记9 4 3 6
- 搜索字符串是否至少包含一次从 0 到 9 的所有数字的最有效方法
- C++ 检查字符串是否至少包含 1 位数字和 1 个字母
- 如何为字符串编写正则表达式,其中包含一个数字至少一个数字,并且不包含任何字母
- 如果QString包含一个数字
- 用于计算不包含给定数字的第n个数字的程序
- 分类包含数字和单词的字符串向量
- 打印每行包含 n 个数字的数组