c编码:统计字符串中中文字符的个数,每个中文字符算一个
时间: 2024-02-18 09:05:05 浏览: 23
可以使用 Unicode 编码的方式来判断一个字符是否为中文字符,中文字符的 Unicode 编码范围为 0x4E00 ~ 0x9FA5。
下面是一个统计字符串中中文字符个数的 C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int is_chinese_char(char c) {
return (c >= 0x4E00 && c <= 0x9FA5);
}
int count_chinese_chars(const char* str) {
int count = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (is_chinese_char(str[i])) {
count++;
}
}
return count;
}
int main() {
const char* str = "Hello, 你好!";
int count = count_chinese_chars(str);
printf("中文字符个数为:%d\n", count);
return 0;
}
```
在上面的代码中,`is_chinese_char` 函数用于判断一个字符是否为中文字符,`count_chinese_chars` 函数用于统计字符串中中文字符的个数。在 `main` 函数中,我们定义了一个包含中文字符的字符串,并调用了 `count_chinese_chars` 函数来统计其中的中文字符个数。