C语言 计算汉字长度
时间: 2023-02-12 13:39:41 浏览: 124
在 C 语言中,可以使用函数 `strlen` 来计算字符串的长度。但是,由于汉字是多字节字符,所以直接使用 `strlen` 函数计算汉字的长度是不准确的。
要正确计算汉字的长度,需要使用特定的函数或者手动遍历字符串,依次判断每个字符是否为汉字。
具体来说,可以使用如下方法计算汉字的长度:
1. 使用函数 `mblen`:
```c
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <wctype.h>
int main() {
setlocale(LC_ALL, "zh_CN.utf8");
const char* str = "你好,世界!";
int len = 0;
for (const char* p = str; *p != '\0'; p += mblen(p, MB_CUR_MAX)) {
if (iswprint(btowc(*p))) {
++len;
}
}
printf("汉字长度:%d\n", len);
return 0;
}
```
2. 使用函数 `mbtowc`:
```c
#include <stdio.h>
#include <string.h>
#include <wchar.h>
int main() {
setlocale(LC_ALL, "zh_CN.utf8");
const char* str = "你好,世界!";
int len = 0;
wchar_t wc;
for (const char* p = str; *p != '\0'; p += mbtowc(&wc, p, MB_CUR_MAX)) {
if (iswprint(wc)) {
++len;
}
}
printf("汉字长度:%d\n", len);
return 0;
}
```
3. 手动遍历字符串:
```c
#include <stdio.h>
#include <string.h>
int main() {
const char* str = "你好,世界!";