c编码:统计其他字符(每个中文字符算1个)的个数,去除大小写字母,数字,空格
时间: 2023-12-15 21:04:39 浏览: 37
以下是一个统计其他字符(每个中文字符算 1 个)个数的代码,并去除大小写字母、数字和空格:
```
#include <stdio.h>
#include <ctype.h>
int main() {
int chinese = 0, other = 0;
char c;
while ((c = getchar()) != EOF) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || isdigit(c) || isspace(c)) {
continue;
} else if (c < 0) { // 中文字符占两个字节,判断第一个字节是否小于 0 即可
chinese++;
} else {
other++;
}
}
printf("chinese: %d, other: %d\n", chinese, other);
return 0;
}
```
该代码利用了字符编码的特性,对于中文字符,它们的编码范围是 0x4E00 ~ 0x9FA5,且每个中文字符占两个字节。因此,我们可以通过判断字符是否小于 0 来判断它是否为中文字符。对于其他字符,我们可以通过判断它是否为字母、数字或空格,来进行过滤。
相关问题
用C语言实现:统计该字符串中的英文字母(包括大小写)、数字、空格、其他字符(每个中文字符算1个)的个数
以下是用C语言实现的程序,可以统计一个字符串中英文字母(包括大小写)、数字、空格、其他字符(每个中文字符算1个)的个数:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int letter_count = 0, digit_count = 0, space_count = 0, other_count = 0, chinese_count = 0;
printf("请输入一个字符串: ");
fgets(str, 100, stdin);
for(int i = 0; str[i] != '\0'; i++) {
if(isalpha(str[i]))
letter_count++;
else if(isdigit(str[i]))
digit_count++;
else if(isspace(str[i]))
space_count++;
else if(str[i] >= 0x4E00 && str[i] < 0x9FA5)
chinese_count++;
else
other_count++;
}
printf("英文字母个数: %d\n", letter_count);
printf("数字个数: %d\n", digit_count);
printf("空格个数: %d\n", space_count);
printf("其他字符个数: %d\n", other_count);
printf("中文字符个数: %d\n", chinese_count);
return 0;
}
```
程序首先读入一个字符串,然后遍历字符串,判断每个字符属于哪一类,分别累加计数器。其中,isalpha函数用于判断字符是否为字母,isdigit函数用于判断字符是否为数字,isspace函数用于判断字符是否为空格。中文字符的判断使用了Unicode编码的范围。最后,程序输出各类字符的个数。
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()` 函数来判断字符的类型,并统计了各个类型字符出现的次数。其中,对于空格字符,我们还需要判断是否为换行符。最后,我们输出了统计结果。