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

时间:2019-06-23 05:54:49

标签: c utf-8 char

因此,我正在尝试根据二进制表示形式确定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字符? / p>

1 个答案:

答案 0 :(得分:5)

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

在Python中,Unicode字符串比在C中更易于检查,因此这是使用内置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
相关问题