【问题标题】:How to transliterate ASCII control characters to their UTF-8 symbolic equivalent?如何将 ASCII 控制字符音译为它们的 UTF-8 符号等价物?
【发布时间】:2021-02-16 14:29:50
【问题描述】:

我想将控制字符范围(0x00 NUL 到 0x1F)中的任何字符音译为编码为 UTF-8 的字符的 Unicode 符号。你有一个简单/优雅的 C++ 解决方案吗?

例子:

不要在字符串中打印“\n”,而是将其替换为“N-L”控制符号,并对所有不可打印的字符执行此操作。

␋␌␍␇␍␑␌␔␈␘␕␖ʬ␄␓␕␊

【问题讨论】:

    标签: c++


    【解决方案1】:
    std::string ReplaceASCIIControlCharacters(std::string input)
    {
        std::vector<uint8_t> output;
        output.reserve(input.length());
        for (char c : input) {
            if (c >= 0x00 && c <= 0x1F) {
                output.push_back(0xe2);
                output.push_back(0x90);
                output.push_back(0x80 + c);
            } else {
                output.push_back(c);
            }
        }
    
        return std::string(output.begin(), output.end());
    }
    

    评论者的改进建议

    std::string output;
    output.reserve(input.length()); 
    for (char c : input) { 
        if (c >= 0x00 && c <= 0x1F) {         
            output.append({0xe2, 0x90, 0x80 + c}); 
        } else { 
            output.push_back(c);
        } 
    } 
    
    return output;
    

    【讨论】:

    • output.assign(output.end(), {0xex, 0x90, 0x80+c}); - 可能会更有效。
    • @MSalters 没有采用这些参数的string::assign() 重载。我想你的意思是string::insert()。甚至只是string::append()
    • 请问您为什么使用临时的vector 而不是直接构建返回的字符串?
    • 好的 - 所以这里的想法是我会提供一个答案的草图,其他人会回答它 - 理想情况下以更好的方式。我刚刚破解了这个 - 目前我需要将它作为 PoC 来做。我不打算接受我的答案作为规范答案。
    • @CameronLowellPalmer 并没有比您介绍的更简单。不过,就像 Bob 建议的那样,您根本不需要 vectorstd::string output; output.reserve(input.length()); for (char c : input) { if (c &gt;= 0x00 &amp;&amp; c &lt;= 0x1F) { output.append({0xe2, 0x90, 0x80 + c}); } else { output.push_back(c); } } return output;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2012-08-02
    相关资源
    最近更新 更多