Skip to content

Instantly share code, notes, and snippets.

@zerhacken
Last active August 1, 2019 04:05
Show Gist options
  • Save zerhacken/48e5e3d521bb4c4977358d8f7b5e1439 to your computer and use it in GitHub Desktop.
Save zerhacken/48e5e3d521bb4c4977358d8f7b5e1439 to your computer and use it in GitHub Desktop.
std::wstring to std::string
#include <iostream>
#include <string>
#include <cassert>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
std::string AsStdStringByConverter(std::wstring ws)
{
using convert_type = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;
// converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
return converter.to_bytes(ws);
}
//std::string AsStdStringByConverter(std::wstring& wstring)
//{
// using convert_type = std::codecvt<wchar_t, char, std::mbstate_t>;
// std::wstring_convert<convert_type, wchar_t> converter;
// return converter.to_bytes(wstring);
//}
std::string AsStdStringByRaw(std::wstring ws)
{
return std::string((const char*)&ws[0], sizeof(wchar_t) / sizeof(wchar_t) * ws.size());
}
std::string AsStdStringConstructed(std::wstring ws)
{
return std::string(ws.begin(), ws.end());
}
int main()
{
std::wstring ws0 = L"Hællo";
// UTF-8
std::string utf8_s0 = AsStdStringByConverter(ws0);
std::string utf8_s1 = AsStdStringByRaw(ws0);
std::string utf8_s2 = AsStdStringConstructed(ws0);
std::cout << "utf8_s0: " << utf8_s0 << ", size: " << utf8_s0.size() << std::endl;
std::cout << "utf8_s1: " << utf8_s1 << ", size: " << utf8_s1.size() << std::endl;
std::cout << "utf8_s2: " << utf8_s2 << ", size: " << utf8_s2.size() << std::endl;
std::wstring ws1 = L"\x0040\x03A6\x0298";
// UTF-16
std::string utf16_s0 = AsStdStringByConverter(ws1);
std::string utf16_s1 = AsStdStringByRaw(ws1);
std::string utf16_s2 = AsStdStringConstructed(ws1);
std::cout << "utf16_s0: " << utf16_s0 << ", size: " << utf16_s0.size() << std::endl;
std::cout << "utf16_s1: " << utf16_s1 << ", size: " << utf16_s1.size() << std::endl;
std::cout << "utf16_s2: " << utf16_s2 << ", size: " << utf16_s2.size() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment