如何将wstring转换为u16string?

D.A*_*ANG 4 c++ winapi utf-16 wstring valueconverter

我想转换wstringu16stringC ++。

我可以转换wstring为字符串,也可以反转。但我不知道如何转换为u16string

u16string CTextConverter::convertWstring2U16(wstring str)

{

        int iSize;
        u16string szDest[256] = {};
        memset(szDest, 0, 256);
        iSize = WideCharToMultiByte(CP_UTF8, NULL, str.c_str(), -1, NULL, 0,0,0);

        WideCharToMultiByte(CP_UTF8, NULL, str.c_str(), -1, szDest, iSize,0,0);
        u16string s16 = szDest;
        return s16;
}
Run Code Online (Sandbox Code Playgroud)

WideCharToMultiByte(CP_UTF8,NULL,str.c_str(),-1,szDest,iSize,0,0);中的错误szDestu16string无法与使用的原因LPSTR

如何解决此代码?

zet*_*t42 7

对于独立平台的解决方案,请参见此答案

如果仅需要Windows平台的解决方案,则下面的代码就足够了:

std::wstring wstr( L"foo" );
std::u16string u16str( wstr.begin(), wstr.end() );
Run Code Online (Sandbox Code Playgroud)

在Windows平台上,std::wstring可以与互换使用,std::u16string因为sizeof(wstring::value_type) == sizeof(u16string::value_type)两者都是UTF-16(小尾数)编码的。

wstring::value_type = wchar_t
u16string::value_type = char16_t
Run Code Online (Sandbox Code Playgroud)

唯一的区别wchar_t是带符号的,而无char16_t符号的,因此您只需要进行符号转换,就可以使用将w16string迭代器对作为参数的构造函数来执行。此构造函数将隐式转换wchar_tchar16_t

完整的示例控制台应用程序:

#include <windows.h>
#include <string>

int main()
{
    static_assert( sizeof(std::wstring::value_type) == sizeof(std::u16string::value_type),
        "std::wstring and std::u16string are expected to have the same character size" );

    std::wstring wstr( L"foo" );
    std::u16string u16str( wstr.begin(), wstr.end() );

    // The u16string constructor performs an implicit conversion like:
    wchar_t wch = L'A';
    char16_t ch16 = wch;

    // Need to reinterpret_cast because char16_t const* is not implicitly convertible
    // to LPCWSTR (aka wchar_t const*).
    ::MessageBoxW( 0, reinterpret_cast<LPCWSTR>( u16str.c_str() ), L"test", 0 );

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • @Davislor 感谢您指出这一点!我知道这一点,这就是为什么我把 `static_assert` 放在那里。作为OP用“winapi”标记的问题,我认为简单的转换就足够了。但使用独立于平台的代码来获得答案也很有用。 (2认同)
  • 对于其他类型:基本类型“char16_t”的编码字节顺序(字节序)取决于系统的字节序。通过说“在 Windows 平台上,`std::wstring` 和 `u16string` 都是 UTF-16 (little endian) 编码”,这表明大多数 Windows 都安装在 x86 (little endian) 上。 (2认同)