我搜索了很多,但找不到任何东西:
unsigned int unicodeChar = 0x5e9;
unsigned int utf8Char;
uni2utf8(unicodeChar, utf8Char);
assert(utf8Char == 0xd7a9);
是否有实现类似于uni2utf8的库(最好是 boost) ?
Unicode 转换是 C++11 的一部分:
#include <codecvt>
#include <locale>
#include <string>
#include <cassert>
int main() {
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
std::string utf8 = convert.to_bytes(0x5e9);
assert(utf8.length() == 2);
assert(utf8[0] == '\xD7');
assert(utf8[1] == '\xA9');
}
Boost.Locale 也有编码转换的功能:
#include <boost/locale.hpp>
int main() {
unsigned int point = 0x5e9;
std::string utf8 = boost::locale::conv::utf_to_utf<char>(&point, &point + 1);
assert(utf8.length() == 2);
assert(utf8[0] == '\xD7');
assert(utf8[1] == '\xA9');
}
您可能想尝试一下UTF8-CPP library。用它编码一个 Unicode 字符看起来像这样:
std::wstring unicodeChar(L"\u05e9");
std::string utf8Char;
encode_utf8(unicodeChar, utf8Char);
std::string
在这里用作 UTF-8 字节的容器。
使用sprintf。(:
cstring = sprintf("%S", unicodestring);