Search code examples
c++unicodecharlocalec++builder

convert unicode to char


How can I convert a Unicode string to a char* or char* const in embarcadero c++ ?


Solution

  • "Unicode string" really isn't specific enough to know what your source data is, but you probably mean 'UTF-16 string stored as wchar_t array' since that's what most people who don't know the correct terminology use.

    "char*" also isn't enough to know what you want to target, although maybe "embarcadero" has some convention. I'll just assume you want UTF-8 data unless you mention otherwise.

    Also I'll limit my example to what works in VS2010

    // your "Unicode" string
    wchar_t const * utf16_string = L"Hello, World!";
    
    // #include <codecvt>
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> convert;
    
    std::string utf8_string = convert.to_bytes(utf16_string);
    

    This assumes that wchar_t strings are UTF-16, as is the case on Windows, but otherwise is portable code.