If I have a UTF-8 std::string
how do I convert it to a UTF-16 std::wstring
? Actually, I want to compare two Persian words.
Both std::string and std::wstring must use UTF encoding to represent Unicode. On macOS specifically, std::string is UTF-8 (8-bit code units), and std::wstring is UTF-32 (32-bit code units); note that the size of wchar_t is platform-dependent.
If you don't like my code then you may use almost-single-header C++ library utfcpp, which should be very well tested by many customers. To convert UTF-8 to UTF-16 just call Utf32To16(Utf8To32(str)) and to convert UTF-16 to UTF-8 call Utf32To8(Utf16To32(str)) .
The easiest solution is to use Unicode string literals and std::wstring: wstring z = L"nüşabə"; CString cs(z. c_str()); nameData. SetWindowTextW(cs);
std::string doesn't have the concept of encodings. It just stores whatever is passed to it. cout <<'è';
This is how you do it with C++11:
std::string str = "your string in utf8"; std::wstring_convert<std::codecvt_utf8_utf16<char16_t>> converter; std::wstring wstr = converter.from_bytes(str);
And these are the headers you need:
#include <iostream> #include <string> #include <locale> #include <codecvt>
A more complete example available here: http://en.cppreference.com/w/cpp/locale/wstring_convert/from_bytes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With