c语言while循环编写统计字符串中英文字母、空格、数字和其他字母个数
时间: 2023-05-28 08:04:56 浏览: 86
```c
#include <stdio.h>
int main()
{
char str[100];
int i = 0, letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入字符串:");
gets(str);
while(str[i] != '\0')
{
if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
letters++;
}
else if(str[i] == ' ')
{
spaces++;
}
else if(str[i] >= '0' && str[i] <= '9')
{
digits++;
}
else
{
others++;
}
i++;
}
printf("字母个数:%d\n空格个数:%d\n数字个数:%d\n其他字符个数:%d\n", letters, spaces, digits, others);
return 0;
}
```
相关问题
用C语言while循环条件为\n输入一行字符分别统计其中的中英文字母,空格,数字和其它字符的个数
可以使用C语言中的字符处理函数来判断输入字符的种类,统计个数。具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char c;
int alphabets = 0, digits = 0, spaces = 0, others = 0;
printf("Please enter a string: ");
while ((c = getchar()) != '\n') {
if (isalpha(c)) {
alphabets++;
} else if (isdigit(c)) {
digits++;
} else if (isspace(c)) {
spaces++;
} else {
others++;
}
}
printf("Alphabets: %d\n", alphabets);
printf("Digits: %d\n", digits);
printf("Spaces: %d\n", spaces);
printf("Others: %d\n", others);
return 0;
}
```
在这个代码中,我们使用了 `getchar()` 函数来逐个读取输入字符,当读取到换行符 `\n` 时,停止循环。在循环中,使用了 `isalpha()` 函数来判断输入字符是否为英文字母,使用了 `isdigit()` 函数来判断输入字符是否为数字,使用了 `isspace()` 函数来判断输入字符是否为空格。如果以上三个函数都返回 `false`,则说明输入字符是其他字符。最后,输出统计结果。
输入一行字符,分别统计其中英文字母、空格、数字和其他字符的个数c语言
实现如下:
```c
#include <stdio.h>
#include <ctype.h> // 用于判断字符的类型
int main()
{
int letter = 0; // 英文字母数
int space = 0; // 空格数
int digit = 0; // 数字数
int other = 0; // 其他字符数
char ch;
printf("请输入一行字符:\n");
while ((ch = getchar()) != '\n') {
if (isalpha(ch)) { // 判断是否是英文字母
letter++;
} else if (isspace(ch)) { // 判断是否是空格
space++;
} else if (isdigit(ch)) { // 判断是否是数字
digit++;
} else { // 其他字符
other++;
}
}
printf("英文字母个数:%d\n", letter);
printf("空格个数:%d\n", space);
printf("数字个数:%d\n", digit);
printf("其他字符个数:%d\n", other);
return 0;
}
```
其中,使用了 `<ctype.h>` 中的三个函数:
- `isalpha()`:判断一个字符是否是英文字母
- `isspace()`:判断一个字符是否是空格字符(包括空格、制表符、换行符等)
- `isdigit()`:判断一个字符是否是数字字符
其余字符均视为其他字符。
相关推荐













