在 C++11 中,我如何从 UTF-8 编码的 std::string
中获取文本中每个字符的 Unicode 值到 uint32_t
?
类似于:
void f(const std::string &utf8_str)
{
for(???) {
uint32_t code = ???;
/* Do my stuff with the code... */
}
}
假设主机系统语言环境是 UTF-8 有帮助吗? C++11 为该任务提供了哪些标准库工具?
最佳答案
您可以使用提供的转换方面和 std::wstring_convert
将字符串简单地转换为 UTF-32 编码的字符串来自 <locale>
:
#include <codecvt>
#include <locale>
#include <string>
void foo(std::string const & utf8str)
{
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv;
std::u32string utf32str = conv.from_bytes(utf8str);
for (char32_t u : utf32str) { /* ... */ }
}
关于c++ - 如何从 UTF-8 字符串的每个字符中获取 UNICODE 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21711618/