UTF 16 到 UTF8,使用 C++ 中的 utf8 库

UTF 16 to UTF8 using utf8 library in c++

本文关键字:C++ 中的 utf8 使用 UTF8 UTF      更新时间:2023-10-16

我正在使用这个库在C++中从 UTF16 到 UTF8 进行转换。

该示例建议使用以下方法将 utf16 转换为 utf8:

unsigned short utf16string[] = {0x41, 0x0448, 0x65e5, 0xd834, 0xdd1e};
vector<unsigned char> utf8result;
utf16to8(utf16string, utf16string + 5, back_inserter(utf8result));
assert (utf8result.size() == 10);    

其中 UTF16to8 的定义由下式给出:

template <typename u16bit_iterator, typename octet_iterator>
octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result);

我有一个字符数组,其中包含 UTF16 中的字符。如果我不知道 UTF16 字符数组的大小(有效字符数),您能否告诉我是否仍然可以使用此库?

No.显然,您无法对存储在未知大小的容器中的数据执行任何有意义的操作。你应该知道它包含多少元素。

供您参考,您可能可以使用 C++11 中引入的 u16string。

#ifdef   WIN32     
#include <codecvt>
#else
#include <uchar.h>
#endif
string toUTF8(const u16string& u16str) {
    string result;
#ifdef   WIN32  
    wstring_convert<codecvt_utf8_utf16<char16_t>, char16_t> convertor;
    result = convertor.to_bytes(u16str);
#else
    mbstate_t mbs;
    mbrlen(NULL, 0, &mbs);   /* initialize mbs */
    int length = 0;
    char buffer [MB_CUR_MAX];
    for (int i= 0; i < u16str.size(); i++){
        length = c16rtomb(buffer, u16str[i], &mbs);
        if ((length == 0) || (length>MB_CUR_MAX)){
            break;
        }
        for (int j = 0; j < length;j++){
            result += buffer[j];
        }
    }
#endif
    return result;
}