用c语言,输入一行文字,统计并输出大写字母、小写字母、数字及其他字符各有多少个。
时间: 2024-06-14 12:04:45 浏览: 12
以下是用C语言统计并输出大写字母、小写字母、数字及其他字符个数的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char c[80];
char *k = c;
int m = 0, x = 0, n = 0, p = 0, q = 0;
gets(c);
while (*k ! '\0') {
if (*k >= 'A' && *k <= 'Z')
m++;
else if (*k >= 'a' && *k <= 'z')
x++;
else if (*k == ' ' || *k == '\t')
n++;
else if (*k >= '0' && *k <= '9')
p++;
else
q++;
k++;
}
printf("%d %d %d %d %d", m, x, n, p, q);
return 0;
}
```
相关问题
c语言输入一行文字,找出其中大写字母、小写字母、空格、数字以及其他字符各有多少?
好的,这是一个关于C语言的问题。
你可以使用C语言的字符数组和循环语句来实现这个功能。首先,你需要定义一个字符数组来存储输入的一行文字。然后,使用循环逐个读取字符,并且判断它是大写字母、小写字母、空格、数字还是其他字符。可以使用C语言中的 isupper()、islower()、isspace()、isdigit() 等函数来进行判断。最后,统计出每种字符类型出现的次数即可。
以下是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int upper = 0, lower = 0, space = 0, digit = 0, other = 0;
printf("请输入一行文字:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
upper++;
} else if (islower(str[i])) {
lower++;
} else if (isspace(str[i])) {
space++;
} else if (isdigit(str[i])) {
digit++;
} else {
other++;
}
}
printf("大写字母:%d\n", upper);
printf("小写字母:%d\n", lower);
printf("空格:%d\n", space);
printf("数字:%d\n", digit);
printf("其他字符:%d\n", other);
return 0;
}
```
希望能对你有所帮助!
输入一行文字,统计并输出其中大写字母、小写字母、空格、数字以及其它字符各有多少,要求用c语言指针方法编程实现。
好的,我可以帮您解答这个问题。以下是实现代码:
```c
#include <stdio.h>
void count_chars(char *str, int *upper, int *lower, int *space, int *digit, int *other)
{
while (*str != '\0')
{
if (*str >= 'A' && *str <= 'Z')
(*upper)++;
else if (*str >= 'a' && *str <= 'z')
(*lower)++;
else if (*str == ' ')
(*space)++;
else if (*str >= '0' && *str <= '9')
(*digit)++;
else
(*other)++;
str++;
}
}
int main()
{
char str[100];
int upper = 0, lower = 0, space = 0, digit = 0, other = 0;
printf("请输入一行文字:");
fgets(str, 100, stdin);
count_chars(str, &upper, &lower, &space, &digit, &other);
printf("大写字母:%d\n", upper);
printf("小写字母:%d\n", lower);
printf("空格:%d\n", space);
printf("数字:%d\n", digit);
printf("其它字符:%d\n", other);
return 0;
}
```
在这个程序中,我们定义了一个 `count_chars` 函数,它的参数包括输入的字符串以及五个指针,分别用于记录大写字母、小写字母、空格、数字和其它字符的数量。这个函数通过循环遍历字符串中的每一个字符,并根据字符的种类更新对应的指针变量。
在 `main` 函数中,我们首先读入用户输入的字符串,然后调用 `count_chars` 函数来统计各种字符的数量。最后,我们输出统计结果。
注意,我们使用了 `fgets` 函数来读入用户输入的字符串,这是为了避免使用 `scanf` 函数时可能会出现的缓冲区溢出问题。