C++ – 将Unicode std::wstring字符串转换为Unicode std::string转义字符,类似于\uxxxx的形式
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – 将Unicode std::wstring字符串转换为Unicode std::string转义字符,类似于\uxxxx的形式
原文链接:https://www.stubbornhuang.com/1858/
发布于:2021年12月10日 13:17:14
修改于:2021年12月10日 13:17:14

1 将Unicode字符转换为\uxxxx转义字符
实现效果:
将:
你好
转换为:
u4f60\u597d
的形式。
1.1 C++代码
#include <iostream>
#include <sstream>
#include <iomanip>
std::string ConvertWStringToUnicodeEscape(const std::wstring& unicode_str)
{
std::wstring unicode_str_copy = unicode_str;
std::stringstream ss;
for (std::wstring::iterator iter = unicode_str_copy.begin(); iter != unicode_str_copy.end(); ++iter)
{
if (*iter <= 127)
ss << (char)*iter;
else
ss << "\\u" << std::hex << std::setfill('0') << std::setw(4) << (int)*iter;
}
return ss.str();
}
int main()
{
std::wstring inputStr = L"你好世界,helloworld";
std::string unicode_str = ConvertWStringToUnicodeEscape(inputStr);
std::cout << unicode_str << std::endl;
return 0;
}
运行结果:

随便找一个在线Unicode中文互转网站,测试一下:

转换结果是对的。
当前分类随机文章推荐
- C++ - single header跨平台高效开源日志库Easylogging++的配置和使用 阅读420次,点赞0次
- C++ - 左值和右值,右值引用与移动语义的概念与理解 阅读240次,点赞1次
- C++ - sleep睡眠函数总结 阅读930次,点赞0次
- C++11 - override关键字简要介绍 阅读2026次,点赞0次
- C++ - websocket++库的可使用的所有事件总结 阅读89次,点赞0次
- C++ - 最简单的将文本文件的内容一次性读取到std::string的方法 阅读4561次,点赞4次
- C++ - 我在项目实际开发中用到的第三方库/开源项目,涵盖网络、加密解密、GUI、网络、音视频、图片等等 阅读135次,点赞0次
- C++STL容器 - std::map删除指定元素 阅读1742次,点赞0次
- C++11 - 委托机制的实现TinyDelegate 阅读1330次,点赞0次
- C++11/std::thread - 可作为线程函数的几种方式总结 阅读3488次,点赞1次
全站随机文章推荐
- C++ - Windows和Linux系统下获取当前可执行程序的绝对路径 阅读1797次,点赞0次
- 资源分享 - Computational Geometry on Surfaces - Performing Computational Geometry on the Cylinder, the Sphere, the Torus, and the Cone 英文高清PDF下载 阅读1909次,点赞0次
- Python - 类对象/列表/元祖/字典判空的方法 阅读2166次,点赞0次
- 资源分享 – OpenGL Programming Guide (Ninth Edition) OpenGL红宝书英文第9版 英文高清PDF下载 阅读2320次,点赞1次
- Mediapipe - 全身包含身体、手部、面部所有关键点标注位置对应图 阅读5096次,点赞4次
- 资源分享 - OpenGL编程指南(原书第9版)- OpenGL红宝书高清带书签PDF下载 阅读12347次,点赞4次
- C++ - 左值和右值,右值引用与移动语义的概念与理解 阅读240次,点赞1次
- 资源分享 - Game Programming Patterns 英文高清PDF下载 阅读1527次,点赞0次
- 杂谈 - 2021年度总结 阅读1589次,点赞0次
- 网站个性化 - 添加人形时钟 honehone_clock.js 阅读2941次,点赞0次
评论
168