网站首页 网站地图
网站首页 > 伤心文案 > c语言题:输入一个字符串

c语言题:输入一个字符串

时间:2025-03-28 18:15:16

```c

include

include // 用于字符判断函数

include // 用于字符串操作

define MAX_SIZE 100 // 定义最大输入长度

// 函数声明

void countCharacters(const char *str, int *upper, int *lower, int *digit, int *other);

int main() {

char input[MAX_SIZE];

int upper = 0, lower = 0, digit = 0, other = 0;

printf("请输入一个字符串(最多 %d 个字符):", MAX_SIZE - 1);

// 使用fgets读取一行输入,避免gets()的安全风险

if (fgets(input, sizeof(input), stdin) == NULL) {

printf("输入错误!

");

return 1;

}

// 去除输入末尾的换行符

size_t len = strlen(input);

if (len > 0 && input[len - 1] == '\n') {

input[len - 1] = '\0';

}

// 调用统计函数

countCharacters(input, &upper, &lower, &digit, &other);

// 输出结果

printf("大写字母个数:%d

", upper);

printf("小写字母个数:%d

", lower);

printf("数字个数:%d

", digit);

printf("其他字符个数:%d

", other);

printf("输入的字符串:%s

", input);

return 0;

}

// 统计字符个数的函数

void countCharacters(const char *str, int *upper, int *lower, int *digit, int *other) {

for (int i = 0; str[i] != '\0'; i++) {

if (isupper(str[i])) {

(*upper)++;

} else if (islower(str[i])) {

(*lower)++;

} else if (isdigit(str[i])) {

(*digit)++;

} else {

(*other)++;

}

}

}

```

代码说明:

输入处理

使用 `fgets` 函数读取用户输入的字符串,避免使用不安全的 `gets()` 函数。

读取后去除末尾的换行符,确保统计准确性。

字符统计

定义 `countCharacters` 函数,遍历字符串中的每个字符。

使用标准库函数 `isupper`、`islower` 和 `isdigit` 判断字符类型,并分别计数。

结果输出

在 `main` 函数中输出各类字符的个数及输入的完整字符串。

示例运行:

```

请输入一个字符串(最多 100 个字符): Hello, World! 123

大写字母个数:2

小写字母个数:8

数字个数:3

其他字符个数:3

输入的字符串:Hello, World! 123

```

注意事项:

该程序假设输入字符串长度不超过 `MAX_SIZE`(100个字符),可根据需要调整。

若需处理更复杂的字符分类(如标点符号),可在 `else` 分支中添加特定判断逻辑。

希望这个示例能帮助你理解如何用C语言进行字符统计!