c语言输入一行字符,分别统计出其中的大小写英文字母、空格、数字和其他字符的个数
时间: 2023-11-23 09:53:42 浏览: 153
这是一个C语言程序,可以输入一行字符并统计其中的大小写英文字母、空格、数字和其他字符的个数。具体实现方法如下:
```
#include <stdio.h>
int main()
{
char c;
int letters = 0, space = 0, digit = 0, other = 0;
while ((c = getchar()) != '\n')
{
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
letters++;
else if (c >= '0' && c <= '9')
digit++;
else if (c == ' ')
space++;
else
other++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n", letters, space, digit, other);
return 0;
}
```
程序中使用了一个while循环,每次读入一个字符并进行判断,如果是大小写英文字母,则字母数加1;如果是数字,则数字数加1;如果是空格,则空格数加1;否则其他字符数加1。最后使用printf函数输出统计结果。
相关问题
输入一行字符,分别统计出其中的大小写英文字母、空格、数字和其它字符的个数。
以下是C语言实现输入一行字符,分别统计出其中的大小写英文字母、空格、数字和其它字符的个数的代码:
```c
#include <stdio.h>
int main()
{
char c;
int y=0,s=0,k=0,z=0;
printf("请输入一串字符:");
while((c=getchar())!='\n')
{
if(c<='z'&&c>='a'||c<='Z'&&c>='z') y++;
else if(c<='9'&&c>='0') s++;
else if(c==' ') k++;
else z++;
}
printf("英文字母有%d个,数字有%d个,空格有%d个,其他字符有%d个",y,s,k,z);
return 0;
}
```
c语言中统计一个文件的大小写字母,数字,空格,换行及其他字符的个数
可以使用 C 语言的文件操作和字符操作函数来实现统计一个文件中大小写字母、数字、空格、换行及其他字符的个数。
代码如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *fp;
int ch, upper = 0, lower = 0, digit = 0, space = 0, newline = 0, other = 0;
fp = fopen("test.txt", "r");
if(fp == NULL) {
printf("Failed to open file.");
return 0;
}
while((ch = fgetc(fp)) != EOF) {
if(isupper(ch)) {
upper++;
} else if(islower(ch)) {
lower++;
} else if(isdigit(ch)) {
digit++;
} else if(isspace(ch)) {
space++;
if(ch == '\n') {
newline++;
}
} else {
other++;
}
}
printf("Uppercase characters: %d\n", upper);
printf("Lowercase characters: %d\n", lower);
printf("Digits: %d\n", digit);
printf("Spaces: %d\n", space);
printf("Newlines: %d\n", newline);
printf("Other characters: %d\n", other);
fclose(fp);
return 0;
}
```
在这个示例中,我们打开了一个名为 "test.txt" 的文件,并通过 `fgetc()` 函数逐个字符读取了文件中的内容。我们使用 `isupper()`、`islower()`、`isdigit()`、`isspace()` 函数来判断字符的类型,并统计了各个类型字符出现的次数。其中,对于空格字符,我们还需要判断是否为换行符。最后,我们输出了统计结果。