c语言统计各类字符个数
时间: 2024-01-04 08:17:45 浏览: 76
以下是C语言统计各类字符个数的代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
int letter = 0, digit = 0, space = 0, other = 0;
while ((ch = getchar()) != EOF)
{
if (isalpha(ch)) // 判断是否为字母
{
letter++;
}
else if (isdigit(ch)) // 判断是否为数字
{
digit++;
}
else if (isspace(ch)) // 判断是否为空格
{
space++;
}
else // 其他字符
{
other++;
}
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```
相关问题
分类统计各类字符个数C语言
下面是一个简单的 C 代码片段,用于统计给定字符串中每个字符类型(字母、数字、空格等)的出现次数。
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char string[100];
int i, alphabets=0, digits=0, spaces=0, punctuations=0;
printf("Enter a string: ");
fgets(string, sizeof(string), stdin);
for(i=0;string[i]!='\0';i++) {
if(isalpha(string[i]))
alphabets++;
else if(isdigit(string[i]))
digits++;
else if(isspace(string[i]))
spaces++;
else
punctuations++;
}
printf("Alphabets = %d\n", alphabets);
printf("Digits = %d\n", digits);
printf("Spaces = %d\n", spaces);
printf("Punctuations = %d\n", punctuations);
return 0;
}
```
该代码使用了 `ctype.h` 头文件中的函数来检查每个字符。`isalpha()` 函数用于检查字母,`isdigit()` 函数用于检查数字,`isspace()` 函数用于检查空格,而其他字符则被认为是标点符号。通过循环遍历输入的字符串并计算每个字符类别的出现次数,最终将结果打印出来。
c语言统计文本文件中各类字符个数
可以使用C语言中的文件操作和字符数组来实现统计文本文件中各类字符个数的功能。
具体步骤如下:
1. 打开文件并读取文件内容
使用C语言中的文件操作函数,先打开需要统计字符的文本文件,并将文件内容读取到一个字符数组中。
```c
FILE *fp;
char buffer[MAX_SIZE];
int i = 0;
fp = fopen("filename.txt", "r");
if(fp == NULL) {
printf("Unable to open file.\n");
return 0;
}
while((buffer[i] = fgetc(fp)) != EOF) {
i++;
}
buffer[i] = '\0';
fclose(fp);
```
2. 统计各类字符个数
遍历字符数组,对于每个字符进行分类,统计各类字符的出现次数,可以使用一个数组来存储各类字符的个数。
```c
int letter_count = 0, digit_count = 0, space_count = 0, other_count = 0;
for(i = 0; buffer[i] != '\0'; i++) {
if(isalpha(buffer[i])) {
letter_count++;
}
else if(isdigit(buffer[i])) {
digit_count++;
}
else if(isspace(buffer[i])) {
space_count++;
}
else {
other_count++;
}
}
```
3. 输出各类字符个数
最后可以将统计结果输出到控制台或者写入到一个新的文本文件中。
```c
printf("Letter count: %d\n", letter_count);
printf("Digit count: %d\n", digit_count);
printf("Space count: %d\n", space_count);
printf("Other count: %d\n", other_count);
```
完整代码示例:
```c
#include <stdio.h>
#include <ctype.h>
#define MAX_SIZE 1000
int main() {
FILE *fp;
char buffer[MAX_SIZE];
int i = 0;
int letter_count = 0, digit_count = 0, space_count = 0, other_count = 0;
fp = fopen("filename.txt", "r");
if(fp == NULL) {
printf("Unable to open file.\n");
return 0;
}
while((buffer[i] = fgetc(fp)) != EOF) {
i++;
}
buffer[i] = '\0';
fclose(fp);
for(i = 0; buffer[i] != '\0'; i++) {
if(isalpha(buffer[i])) {
letter_count++;
}
else if(isdigit(buffer[i])) {
digit_count++;
}
else if(isspace(buffer[i])) {
space_count++;
}
else {
other_count++;
}
}
printf("Letter count: %d\n", letter_count);
printf("Digit count: %d\n", digit_count);
printf("Space count: %d\n", space_count);
printf("Other count: %d\n", other_count);
return 0;
}
```