【问题标题】:How do you use wstring_convert to convert between utf16 and utf32?如何使用 wstring_convert 在 utf16 和 utf32 之间进行转换?
【发布时间】:2020-07-29 00:08:18
【问题描述】:

当您从std::u16string 转到std::u32string 时,std::wstring_convert 不能像预期的chars 那样工作。那么如何使用std::wstring_convertstd::u16string 作为输入在UTF-16 和UTF-32 之间进行转换呢?

例如:

inline std::u32string utf16_to_utf32(const std::u16string& s) {
    std::wstring_convert<std::codecvt_utf16<char32_t>, char32_t> conv;
    return conv.from_bytes(s); // cannot do this, expects 'char'
}

reinterpret_castchar 可以吗,就像我在几个例子中看到的那样?

如果您确实需要reinterpret_cast,我已经看到了一些使用字符串大小而不是指针总字节大小的示例。这是错误还是要求?

我知道codecvt 已被弃用,但在标准提供替代方案之前,它必须这样做。

【问题讨论】:

    标签: c++11 utf-16 utf-32 codecvt


    【解决方案1】:

    如果您不想reinterpret_cast,我发现的唯一方法是先转换为utf-8,然后再转换为utf-32。

    例如,

    // Convert to utf-8.
    std::u16string s;
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conv;
    std::string utf8_str = conv.to_bytes(s);
    
    // Convert to utf-32.
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv;
    std::u32string utf32_str = conv.from_bytes(utf8_str);
    

    是的,这很可悲,可能会导致 codecvt 被弃用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-05
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 2013-02-15
      • 1970-01-01
      相关资源
      最近更新 更多