c++ - 如何在 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?
解决方案
反斜杠后面的数字是西里尔字母的 UTF-8 字节序列值,每个字节表示为一个八进制数。
例如,您可以使用正则表达式替换每个替换为\ooo
它的值,以便得到一个真正的 UTF-8 字符串:
#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::string
为std::wstring
使用例如Thomas的方法。
推荐阅读
- python - 按类别计算精度和召回率
- angular - 创建组件时,将 [ngClass]="class" 和 [ngStyle]="style" 对元素执行什么操作
- c# - 截取面板截图
- google-apps-script - 谷歌电子表格中的逻辑异常/差异范围
- sql - 试图在同一用户的两个日期之间显示超过一天的数据?
- c# - AvalonDock FloatingWindow 填充内容
- sql - 使用 Soundex 创建一个函数以获取类似的发音词
- python - 如何在 BeautifulSoup 中删除以前的兄弟姐妹
- c# - 如何在 Ninject 的继承树中使用继承的 DbContext 的相同实例?
- spring - 为什么当restTemplate存在两个@Bean方法时Spring Boot应用程序启动