c语言统计文本文件中各类字符个数
时间: 2023-09-27 16:08:18 浏览: 197
可以使用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;
}
```
阅读全文
相关推荐
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)