我想为以下程序获得 5 而不是 10。有人知道如何修复代码来计算多字节字符的数量吗?谢谢。
/* vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8: */
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <locale.h>
size_t nchars(const char *s) {
size_t charlen, chars;
mbstate_t mbs;
chars = 0;
memset(&mbs, 0, sizeof(mbs));
while (
(charlen = mbrlen(s, MB_CUR_MAX, &mbs)) != 0
&& charlen != (size_t)-1
&& charlen != (size_t)-2
) {
s += charlen;
chars++;
}
return (chars);
}
int main() {
setlocale(LC_CTYPE, "en_US.utf8");
char * text = "öçşğü";
printf("%zu\n", nchars (text));
return 0;
}
$ ./main.exe
10