用c语言统计字符个数
时间: 2024-03-13 09:39:02 浏览: 23
以下是用C语言统计字符个数的例子:
```c
#include <stdio.h>
int main() {
char c; //定义字符
int letters=0, space=0, digit=0, other=0; //定义字符初始量数量
while ((c=getchar())!=EOF) //运用循环语句读到文件结尾截止
{
if (c>='a' && c<='z' || c>='A' && c<='Z') //计算大写字母和小写字符数量
letters++;
else if (c==' ') //计算空格数量
space++;
else if (c>='0' && c<='9') //计算数字数量
digit++;
else
other++; //其他字符数量
}
printf("%d %d %d %d", letters, space, digit, other);
return 0;
}
```
相关问题
c语言统计字符串个数
以下是使用C语言统计字符串个数的例子:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int count = 0, i;
printf("请输入一个字符串:");
gets(str);
for(i = 0; str[i] != '\0'; i++){
count++;
}
printf("字符串的字符数为:%d", count);
return 0;
}
```
运行结果:
```
请输入一个字符串:Hello World!
字符串的字符数为:12
```
c语言数组统计字符个数
以下是两种C语言统计字符个数的例子:
1.使用strlen()函数计算字符串长度
```c
#include <stdio.h>
#include <string.h>
int main() {
char a[80];
int count = 0;
gets(a);
count = strlen(a); // 可计算字符串个数
printf("%d", count);
return 0;
}
```
2.使用while循环遍历字符串计算字符个数
```c
#include <stdio.h>
int main() {
char a[80];
int i = 0, count = 0;
gets(a);
while (a[i] != '\0') {
count++;
i++;
}
printf("%d", count);
return 0;
}
```