C语言代码 递归函数 【问题描述】 假定一个系统中要求用户设定各自的密码必须满足下面的要求: 长度至少8位; 不能含有字母和数字以外的字符; 必须至少含有1个字母和1个数字。 下面判断合法性时,请按上面的顺序来判断。 请编写程序判断用户给定的字符串是否是合法的密码,如合法请输出Yes 如不合法请输出错误原因: 长度不合法 invalid length 包含了非法字符 invalid char 仅包含了数字 letter missing 仅包含了字母 number missing 例如,用户输入 helloword, 由于未包含数字所以不合法,应输出 number missing 【样例输入】 a1b 【样例输出】 invalid length 【样例输入】 a1b+a2bcd 【样例输出】 invalid char 【样例输入】 abcdyiuljk 【样例输出】 number missing 【样例输入】 23425234234234 【样例输出】 letter missing 【样例输入】 a1ba2ba3b 【样例输出】 Yes
时间: 2024-01-31 11:02:46 浏览: 26
好的,以下是C语言代码实现:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int is_valid_password(char *str) {
int len = strlen(str);
if (len < 8) { // 判断长度是否不足8位
return 1;
}
for (int i = 0; i < len; i++) {
if (!isalnum(str[i])) { // 判断是否含有字母和数字以外的字符
return 2;
}
}
int letter_count = 0, number_count = 0;
for (int i = 0; i < len; i++) {
if (isalpha(str[i])) { // 统计字母数量
letter_count++;
} else if (isdigit(str[i])) { // 统计数字数量
number_count++;
}
}
if (letter_count == 0 && number_count > 0) { // 判断是否仅包含数字
return 3;
} else if (letter_count > 0 && number_count == 0) { // 判断是否仅包含字母
return 4;
} else if (letter_count == 0 && number_count == 0) { // 判断是否字母和数字都没有
return 2;
}
return 0; // 校验通过,返回0
}
int main() {
char str[100];
printf("请输入密码:\n");
scanf("%s", str);
int result = is_valid_password(str);
switch (result) {
case 1: printf("invalid length"); break;
case 2: printf("invalid char"); break;
case 3: printf("number missing"); break;
case 4: printf("letter missing"); break;
default: printf("Yes"); break;
}
return 0;
}
```
代码思路:
1. 首先让用户输入密码
2. 调用is_valid_password函数判断密码是否合法
3. 首先判断长度是否不足8位
4. 然后判断是否含有字母和数字以外的字符
5. 统计字母和数字的数量,判断是否仅包含数字或仅包含字母
6. 如果校验通过,返回0,否则返回相应的错误代码
7. 根据错误代码输出错误原因
运行结果:
```
请输入密码:
a1b
invalid length
```