代码之家  ›  专栏  ›  技术社区  ›  Kuang

c++在字符串中添加“\u”

  •  -1
  • Kuang  · 技术社区  · 8 年前

    学习c++,尝试通过在“\u”后添加4位数字来显示UTF-16字符。但是,例如,如果我尝试直接添加0000:

    string temp = "\u" + "0000";
    

    我得到的错误是:通用字符名格式不正确。那么有没有办法让这两个字符组成一个Unicode字符呢?我还意识到,最后四个数字的范围是0-F,但现在我只想关注0-9个字符。

    如何使用其他字符串添加“\u”

    编辑:我正在寻找与JavaScript函数相当的C++函数:

    String.fromCharCode()
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   cHao    8 年前

    你不能说 "\u" + "0000" ,因为转义序列的解析发生在过程的早期,即实际编译开始之前。当字符串连接在一起时,转义序列已经被解析,不再被解析。从那以后 \u 本身不是有效的转义序列,您会得到一个错误。

        2
  •  1
  •   user9124890    8 年前

    你想做的是不可能的。C++解析分为多个阶段。根据[法律阶段],转义序列(在阶段5中)被转义 之前 相邻的字符串文字被串联(第6阶段)。

        3
  •  1
  •   Galik    8 年前

    你不能把一个 字符串文字 就像那样。引号中的特殊序列是编译器在编译时插入相关Unicode字符的指令,因此如果将其分成两部分,则不再将其识别为指令。

    按程序 生成 UTF-16 基于其Unicode代码点编号的字符您可以使用标准库Unicode converson函数。不幸的是,两者之间没有直接的转换 UTF-32 (Unicode代码点)和 UTF-16 所以你必须通过 UTF-8 作为中间值:

    // UTF-16 may contain either one or two char16_t characters so
    // we return a string to potentially contain both.
    ///
    std::u16string codepoint_to_utf16(char32_t cp)
    {
        // convert UTF-32 (standard unicode codepoint) to UTF-8 intermediate value
        char utf8[4];
        char* end_of_utf8;
    
        {
            char32_t const* from = &cp;
    
            std::mbstate_t mbs;
            std::codecvt_utf8<char32_t> ccv;
    
            if(ccv.out(mbs, from, from + 1, from, utf8, utf8 + 4, end_of_utf8))
                throw std::runtime_error("bad conversion");
        }
    
        // Now convert the UTF-8 intermediate value to UTF-16
    
        char16_t utf16[2];
        char16_t* end_of_utf16;
    
        {
            char const* from = nullptr;
    
            std::mbstate_t mbs;
            std::codecvt_utf8_utf16<char16_t> ccv;
    
            if(ccv.in(mbs, utf8, end_of_utf8, from, utf16, utf16 + 2, end_of_utf16))
                throw std::runtime_error("bad conversion");
        }
    
        return {utf16, end_of_utf16};
    }
    
    int main()
    {
        std::u16string s; // can hold UTF-16
    
        // iterate through some Greek codepoint values
        for(char32_t u = 0x03b1; u < 0x03c9; ++u)
        {
            // append the converted UTF-16 characters to our string
            s += codepoint_to_utf16(u);
        }
    
        //  do whatever you want with s here...    
    }