Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert UTF-8 std::string to UTF-16 std::wstring?

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.

like image 796
aliakbarian Avatar asked Aug 22 '11 21:08

aliakbarian


People also ask

Is std::string utf8?

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.

How do you convert UTF 16 to UTF-8 in C++?

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)) .

How do I convert Wstring to CString?

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);

What is the encoding of std::string?

std::string doesn't have the concept of encodings. It just stores whatever is passed to it. cout <<'è';


1 Answers

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

like image 63
Yuchen Avatar answered Sep 28 '22 12:09

Yuchen