Home >Backend Development >C++ >How can I efficiently convert a `wstring` to a `string` in C ?

How can I efficiently convert a `wstring` to a `string` in C ?

DDD
DDDOriginal
2024-12-14 15:08:11700browse

How can I efficiently convert a `wstring` to a `string` in C  ?

Converting wstring to string in C

Issue

How can I convert a wstring to a string in C ? Consider the following example:

#include <string>
#include <iostream>

int main() {
    std::wstring ws = L"Hello";
    std::string s(ws.begin(), ws.end());

    std::cout << "std::string =     " << s << std::endl;
    std::wcout << "std::wstring =    " << ws << std::endl;
    std::cout << "std::string =     " << s << std::endl;
}

With the commented-out line, the output is:

std::string =     Hello
std::wstring =    Hello
std::string =     Hello

However, without it, the output is only:

std::wstring =    Hello

Answer

Using std::wstring_convert (C 11)

As pointed out by Cubbi, std::wstring_convert provides an easy solution:

#include <locale>
#include <codecvt>

std::wstring string_to_convert;

using convert_type = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;

// Convert wstring to string
std::string converted_str = converter.to_bytes(string_to_convert);

You can also use helper functions to simplify the conversion:

// Convert string to wstring
std::wstring s2ws(const std::string& str) {
    using convert_typeX = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_typeX, wchar_t> converterX;
    return converterX.from_bytes(str);
}

// Convert wstring to string
std::string ws2s(const std::wstring& wstr) {
    using convert_typeX = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_typeX, wchar_t> converterX;
    return converterX.to_bytes(wstr);
}

The above is the detailed content of How can I efficiently convert a `wstring` to a `string` in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn