gpt4 book ai didi

c - 确定utf-8字符的字节宽度

转载 作者:行者123 更新时间:2023-12-04 12:14:59 26 4
gpt4 key购买 nike

因此,我正在尝试根据二进制表示形式确定utf-8字符的宽度(以字节为单位)。然后,计算utf8字符串中的字符数。下面是我的代码。

#include <stdlib.h>
#include <stdio.h>

static const char* test1 = "发f";
static const char* test2 = "ด้ดีด้ดี";

unsigned utf8_char_size(unsigned char val) {
if (val < 128) {
return 1;
} else if (val < 224) {
return 2;
} else if (val < 240) {
return 3;
} else {
return 4;
}
}

unsigned utf8_count_chars(const unsigned char* data)
{
unsigned total = 0;
while(*data != 0) {
unsigned char_width = utf8_char_size(*data);
total++;
data += char_width;
}
return total;
}

int main(void) {
fprintf(stdout, "The count is %u\n", utf8_count_chars((unsigned char*)test1));
fprintf(stdout, "The count is %u\n", utf8_count_chars((unsigned char*)test2));
return 0;
}


这里的问题是,对于上面的第一个测试运行,我得到 The count is 2。这对于第一个字母是有意义的,但是对于第二个字母 test2,它带有4个泰语字母,则输出8,这是不正确的。

我想知道我的代码在做什么错,而且,我想知道在C中给定的 unsigned char数组,如何将字节作为utf-8字符进行迭代?

最佳答案

该代码的大小为neither characters nor glyphs but code points。一个字符可以由多个Unicode代码点组成。在这种情况下,泰语文字有8个代码点。

与在C语言中相比,在Python中检查Unicode字符串更容易,因此下面是使用内置Unicode数据库进行的Python 3.6小演示:

>>> import unicodedata
>>> for i in 'ด้ดีด้ดี':
... print(f'{ord(i):04X} {unicodedata.name(i)}')
...
0E14 THAI CHARACTER DO DEK
0E49 THAI CHARACTER MAI THO
0E14 THAI CHARACTER DO DEK
0E35 THAI CHARACTER SARA II
0E14 THAI CHARACTER DO DEK
0E49 THAI CHARACTER MAI THO
0E14 THAI CHARACTER DO DEK
0E35 THAI CHARACTER SARA II

关于c - 确定utf-8字符的字节宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56721401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com