如何将wstring转换为u16string? [英] how can I convert wstring to u16string?
问题描述
我想在C ++中将wstring
转换为u16string
.
I want to convert wstring
to u16string
in C++.
我可以将wstring
转换为字符串,也可以反向转换.但是我不知道如何转换为u16string
.
I can convert wstring
to string, or reverse. But I don't know how convert to 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;
}
WideCharToMultiByte(CP_UTF8,NULL,str.c_str(),-1,szDest,iSize,0,0);中的错误szDest
. u16string
的原因不能与LPSTR
一起使用.
Error in WideCharToMultiByte(CP_UTF8, NULL, str.c_str(), -1, szDest, iSize,0,0);'s szDest
. Cause of u16string
can't use with LPSTR
.
如何解决此代码?
推荐答案
有关与平台无关的解决方案,请参见这个答案.
For a platform-independent solution see this answer.
如果仅需要 Windows平台的解决方案,则下面的代码就足够了:
If you need a solution only for the Windows platform, the following code will be sufficient:
std::wstring wstr( L"foo" );
std::u16string u16str( wstr.begin(), wstr.end() );
在Windows平台上,std::wstring
可与std::u16string
互换,因为sizeof(wstring::value_type) == sizeof(u16string::value_type)
且两者都是UTF-16(小尾数)编码的.
On the Windows platform, a std::wstring
is interchangeable with std::u16string
because sizeof(wstring::value_type) == sizeof(u16string::value_type)
and both are UTF-16 (little endian) encoded.
wstring::value_type = wchar_t
u16string::value_type = char16_t
唯一的区别是wchar_t
是带符号的,而char16_t
是无符号的,因此您只需要进行符号转换,可以使用将迭代器对作为参数的w16string
构造函数来执行.此构造函数会将wchar_t
隐式转换为char16_t
.
The only difference being that wchar_t
is signed, whereas char16_t
is unsigned so you only have to do sign conversion, which can be performed using the w16string
constructor that takes an iterator pair as arguments. This constructor will implicitly convert wchar_t
to char16_t
.
完整的示例控制台应用程序:
Full example console application:
#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;
}
这篇关于如何将wstring转换为u16string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!