Home >Backend Development >C++ >How to Efficiently Convert `wstring` to `string` in C ?

How to Efficiently Convert `wstring` to `string` in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 05:08:11488browse

How to Efficiently Convert `wstring` to `string` in C  ?

Converting wstring to string

Problem:
How to effectively convert a wstring to a string in C ?

Context:
In C , wstring and string represent wide character and narrow character strings, respectively. Converting between these two types can be necessary in various scenarios.

Original Attempt:

#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;
}

Issue:
The provided example only outputs the initial wstring value, not the string conversion.

Solution using std::wstring_convert:
C 11 introduced std::wstring_convert, which simplifies the conversion process:

#include <locale>
#include <codecvt>

int main() {
    std::wstring ws = L"Hello";

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

    // Convert wstring to string
    std::string s = converter.to_bytes(ws);

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

One-liner Solution:

std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes("some string");

Wrapper Function Solution:

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

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 to Efficiently Convert `wstring` to `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