c++ - 如何从 UTF-8 字符串的每个字符中获取 UNICODE 代码?

标签 c++ c++11 unicode encoding utf-8

在 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/

相关文章:

c++ - 复制构造函数中的无限递归

c++ - 为什么这个 RAII 只 move 类型不能正确模拟 `std::unique_ptr` ?

c# - 字符串总是 Little Endian Unicode 吗?

javascript - python3 打印函数发出 'ascii' codec can't encode character 错误

c++ - CMake链接图集和llapack

c++ - 什么时候引用函数有用?

c++ - 使用最少的内部内存资源有效地对进出磁盘的字符串进行排序的算法

c++ - 共同的初始序列和比对

c++ - 使用用户定义的文字实现 km/h 和 m/s

PHP 函数 imagettftext() 和 unicode