【问题标题】:converting a chararcter to \uxxx format in C /C++在 C /C++ 中将字符转换为 \use 格式
【发布时间】:2012-03-07 17:34:37
【问题描述】:

我想在 C / C++ 程序中将字符串/字符转换为 \uxxx 格式。 支持 我有一个字符“A”,我想将 convert 打印为 \u0041( 标准 unicode )。

第二件事是我使用 unix 命令实用程序来打印 (printf) 来打印 \uxxx 字符串 tto char。我尝试使用“\u092b”打印与我的字体文件不同的字符。谁能解释一下这背后的原因。

【问题讨论】:

  • 你试过什么没用?
  • 您使用什么内部格式来表示程序内部的字符? ASCII/UTF-8/UTF-16/UTF-32/CP1490/ISO8859-1? \u 格式是否仅支持 4 个十六进制数字或 6 个十六进制数字。如果它只支持 4,那么您将需要编码为 UTF-16(因为您可以用 4 个十六进制数字表示所有代码点)并使用代理对来表示更长的字符。

标签: c++ c unicode


【解决方案1】:

这是一个使用标准 C++ 执行此操作的函数(尽管取决于 CharT,它可能有一些要求,某些有效的实现定义的行为不满足)。

#include <codecvt>
#include <sstream>
#include <iomanip>
#include <iostream>

template<typename CharT,typename traits,typename allocator>
std::basic_string<CharT,traits,allocator>
to_uescapes(std::basic_string<CharT,traits,allocator> const &input)
{
    // string converter from CharT to char. If CharT = char then no conversion is done.
    // if CharT is char32_t or char16_t then the conversion is UTF-32/16 -> UTF-8. Not all implementations support this yet.
    // if CharT is something else then this uses implementation defined encodings and will only work for us if the implementation uses UTF-8 as the narrow char encoding
    std::wstring_convert<std::codecvt<CharT,char,std::mbstate_t>,CharT> convertA;

    // string converter from UTF-8 -> UTF-32. Not all implementations support this yet
    std::wstring_convert<std::codecvt<char32_t,char,std::mbstate_t>,char32_t> convertB;

    // convert from input encoding to UTF-32 (Assuming convertA produces UTF-8 string)
    std::u32string u32input = convertB.from_bytes(convertA.to_bytes(input));

    std::basic_stringstream<CharT,traits,allocator> ss;
    ss.fill('0');
    ss << std::hex;
    for(char32_t c : u32input) {
        if(c < U'\U00010000')
            ss << convertA.from_bytes("\\u") << std::setw(4) << (unsigned int)c;
        else
            ss << convertA.from_bytes("\\U") << std::setw(8) << (unsigned int)c;
    }
    return ss.str();
}

template<typename CharT>
std::basic_string<CharT>
to_uescapes(CharT const *input)
{
    return to_uescapes(std::basic_string<CharT>(input));
}

int main() {
    std::string s = to_uescapes(u8"Hello \U00010000");
    std::cout << s << '\n';
}

这应该打印出来:

\u0048\u0065\u006c\u006c\u006f\u0020\U00010000

【讨论】:

  • 我无法在 ubuntu 上编译它,因为没有 codecvt 头文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
相关资源
最近更新 更多