首页 > 解决方案 > 如何在 C++ 中将“\320\272\320\276\320\274...”之类的文本转换为 std::wstring?

问题描述

我正在处理处理来自 Ubuntu 的消息的代码,其中一些消息包含,例如:

localhost sshd 1658 - - 来自 172.28.60.28 端口 50712 的无效用户 \320\272\320\276\320\274\320\274\321\320\275\320\270\320\267\320\274 ]

其中“\320\272\320\276\320\274\320\274\321\320\275\320\270\320\267\320\274”是最初使用俄语的用户名。如何将其转换为 std::wstring?

标签: c++utf-8

解决方案


反斜杠后面的数字是西里尔字母的 UTF-8 字节序列值,每个字节表示为一个八进制数。

例如,您可以使用正则表达式替换每个替换为\ooo它的值,以便得到一个真正的 UTF-8 字符串:

在 Wandbox 上查看

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main()
{
    std::string const source = R"(Invalid user \320\272\320\276\320\274\320\274\321\320\275\320\270\320\267\320\274 from 172.28.60.28 port 50712)";
    boost::regex const re(R"(\\\d\d\d)");

    auto const replacer = [](boost::smatch const& match, auto it) {
        auto const byteVal = std::stoi(&match[0].str()[1], 0, 8);
        *it = static_cast<char>(byteVal);
        return ++it;
    };
    std::string const out = boost::regex_replace(source, re, replacer);

    std::cout << out << std::endl;
    return EXIT_SUCCESS;
}

如果您确实需要,您可以将其转换std::stringstd::wstring使用例如Thomas的方法。


推荐阅读