#include <Windows.h>
#include <codecvt>
#include <iomanip>
#include <iostream>
#include <locale>
#include <sstream>
std::wstring String2Wstring(const std::string &utf8String)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return (converter.from_bytes(utf8String));
}
std::string ConvertUnicodeEscape(const std::string &unicode_str)
{
std::wstring unicode_wstr = String2Wstring(unicode_str);
std::stringstream ss;
for (auto iter = unicode_wstr.cbegin(); iter != unicode_wstr.cend(); ++iter) {
if (*iter < 128) {
ss << (char)*iter;
} else {
ss << "\\u" << std::hex << std::setfill('0') << std::setw(4) << (int)*iter;
}
}
return ss.str();
}
std::string ConvertUnicodeEscape(const std::wstring &unicode_wstr)
{
std::stringstream ss;
for (auto iter = unicode_wstr.cbegin(); iter != unicode_wstr.cend(); ++iter) {
if (*iter < 128) {
ss << (char)*iter;
} else {
ss << "\\u" << std::hex << std::setfill('0') << std::setw(4) << (int)*iter;
}
}
return ss.str();
}
int main()
{
std::string input_str = "测试_123.txt";
std::cout << "string to unicode:" << ConvertUnicodeEscape(input_str) << std::endl;
std::wstring input_wstr = L"测试_123.txt";
std::cout << "wstring to unicode:" << ConvertUnicodeEscape(input_wstr) << std::endl;
return 0;
}
运行结果: