利用C语言输入一行字符分别统计出其中的大写字母、小写字母、数字和其他字符的个数
时间: 2023-12-14 14:03:00 浏览: 47
下面是利用C语言输入一行字符分别统计出其中的大写字母、小写字母、数字和其他字符的个数的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
char c;
int upper = 0, lower = 0, digit = 0, other = 0;
printf("请输入一行字符:\n");
while ((c = getchar()) != '\n')
{
if (isupper(c))
upper++;
else if (islower(c))
lower++;
else if (isdigit(c))
digit++;
else
other++;
}
printf("大写字母:%d\n", upper);
printf("小写字母:%d\n", lower);
printf("数字:%d\n", digit);
printf("其他字符:%d\n", other);
return 0;
}
```
相关问题
输入一行字符分别统计出其中英文大写字母和小写字母的个数,C语言
好的,以下是 C 语言代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int upper_count = 0, lower_count = 0, i = 0;
printf("请输入一行字符:");
fgets(str, 100, stdin); // 使用 fgets() 获取用户输入的字符串
while (str[i] != '\0') { // 遍历字符串
if (isupper(str[i])) {
upper_count++;
} else if (islower(str[i])) {
lower_count++;
}
i++;
}
printf("大写字母个数:%d\n", upper_count);
printf("小写字母个数:%d\n", lower_count);
return 0;
}
```
这段代码首先定义了一个字符数组 `str`,用于存放用户输入的字符串。然后使用 `fgets()` 函数获取用户输入的一行字符串。接着使用 `while` 循环遍历这个字符串中的每个字符,如果是大写字母则将 `upper_count` 计数器加 1,如果是小写字母则将 `lower_count` 计数器加 1。最后输出结果即可。需要注意的是,为了避免用户输入超过字符数组 `str` 的长度,应该设置合适的数组长度,并且使用 `fgets()` 函数获取字符串。
c语言输入一行字符,分别统计出其中的大写英文字母、小写英文字母、空格、数字和其他字符的个数
这段代码是一个C语言程序,可以输入一行字符并统计其中的大写英文字母、小写英文字母、空格、数字和其他字符的个数。具体实现方法如下:
1. 定义四个整型变量letters、space、digit、others,分别表示字母、空格、数字和其他字符的个数。
2. 使用getchar()函数逐个读取输入的字符,直到读取到回车符为止。
3. 对于每个读取到的字符,使用if语句进行判断,如果是大写字母或小写字母,则将letters加1;如果是空格,则将space加1;如果是数字,则将digit加1;否则将others加1。
4. 最后使用printf()函数输出四种类型的输入内容的个数。
下面是代码实现:
```
#include <stdio.h>
int main()
{
char c;
int letters = 0, space = 0, digit = 0, others = 0;
printf("请输入一行字符:\n");
while ((c = getchar()) != '\n')
{
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
letters++;
else if (c == ' ')
space++;
else if (c >= '0' && c <= '9')
digit++;
else
others++;
}
printf("大写字母:%d\n", letters);
printf("小写字母:%d\n", letters);
printf("空格:%d\n", space);
printf("数字:%d\n", digit);
printf("其他字符:%d\n", others);
return 0;
}
```