簡體   English   中英

在C ++中使用utf8庫將UTF 16轉換為UTF8

[英]UTF 16 to UTF8 using utf8 library in c++

我正在使用庫在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);

我有一個char數組,其中包含UTF16中的字符。 如果我不知道我的UTF16字符數組的大小(有效字符數),能否告訴我是否仍然可以使用該庫?

不能。顯然,您無法對大小未知的容器中存儲的數據做任何有意義的事情。 應該知道它包含多少元素。

供您參考,可能可以使用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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM