【发布时间】:2020-02-08 13:48:46
【问题描述】:
我正在使用 C++11 中的 Unicode,我现在无法将 std::string 转换为 std::u32string。
我的代码如下:
#include <iostream>
#include <string>
#include <locale>
#include "unicode/unistr.h"
#include "unicode/ustream.h"
int main()
{
constexpr char locale_name[] = "";
setlocale( LC_ALL, locale_name );
std::locale::global(std::locale(locale_name));
std::ios_base::sync_with_stdio(false);
std::wcin.imbue(std::locale());
std::wcout.imbue(std::locale());
std::string str="hello☺????";
std::u32string s(str.begin(),str.end());
icu::UnicodeString ustr = icu::UnicodeString::fromUTF32(reinterpret_cast<const UChar32 *>(s.c_str()), s.size());
std::cout << "Unicode string is: " << ustr << std::endl;
std::cout << "Size of unicode string = " << ustr.countChar32() << std::endl;
std::cout << "Individual characters of the string are:" << std::endl;
for(int i=0; i < ustr.countChar32(); i++)
std::cout << icu::UnicodeString(ustr.char32At(i)) << std::endl;
return 0;
}
执行时的输出是:(这不是预期的)
Unicode string is: hello�������
Size of unicode string = 12
Individual characters of the string are:
h
e
l
l
o
�
�
�
�
�
�
�
请建议是否存在为此的任何 ICU 库函数
【问题讨论】:
-
使用 UTF-32 有什么意义吗?
-
既然有一个
fromUTF32函数,那么在某个地方也应该有一个toUTF32。这是您将std::string转换为std::u3string所需要的。将std::string的每个字符复制到std::u32string中的每个 unicode 值不会完成任何有用的操作。 -
你可以在下面的帖子中调整
widen函数来做你想做的事:stackoverflow.com/questions/51210723/how-to-detect-â€-combination-of-unicode-in-c-string/51212415#51212415 -
ICU 使用 UTF-16 表示。
str在您的示例中不是 UTF-32 编码的。为什么又要在任一方向使用 UTF-32?str很可能是 UTF-8 格式,而您想要UnicodeString::fromUTF8 -
@dashthird 今天没有人使用 UTF-32。如果在操作系统中,请使用 UTF-16。如果在 Web 中,请使用 UTF-8。您极不可能遇到 BMP 之外的某些字符,因此 UTF-16 就不够用了。
标签: c++ c++11 unicode non-ascii-characters icu