Home >Backend Development >C++ >How to Convert Between UTF-8 and Wide Character Strings in C ?
UTF8 to/from Wide Char Conversion in STL
Converting Unicode text represented as UTF-8 strings in std::string to wide character strings in std::wstring and vice versa is essential for platform-independent programming. Here's how to achieve this using the C Standard Library:
UTF-8 to UTF-16
C 11 introduced std::wstring_convert, which facilitates conversions between narrow and wide character strings:
std::string utf8Source; ... std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter; std::u16string utf16Destination = converter.from_bytes(utf8Source);
UTF-16 to UTF-8
The conversion from UTF-16 to UTF-8 is similar:
std::u16string utf16Source; ... std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter; std::string utf8Destination = converter.to_bytes(utf16Source);
This approach utilizes the C Standard Library's powerful std::wstring_convert facility, offering a standardized and efficient solution for multi-platform UTF8-wide char conversions.
The above is the detailed content of How to Convert Between UTF-8 and Wide Character Strings in C ?. For more information, please follow other related articles on the PHP Chinese website!