UTF 16 到 UTF8,使用 C++ 中的 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);
我有一个字符数组,其中包含 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;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 将值指定给向量(2D)的向量中的某个位置
- 内置函数可查看CPP中的成员变量