char、wchar_t、char16_t 、char32_t与 string、wsting、u16string、u32string

C++编程语言中,char有一个字节表示,wchar_t宽体字符,由两个字符表示。char16_t,char32_t C++ 11新增的字符类型,char16_t占两个字节,char32_t占四个字节。

#include <string>
#include <codecvt>
#include <locale>
#include <iostream>

using namespace std;

std::u16string to_utf16( std::string str )
{ return std::wstring_convert< std::codecvt_utf8_utf16<char16_t>, char16_t >{}.from_bytes(str); }
 
std::string to_utf8( std::u16string str16 )
{ return std::wstring_convert< std::codecvt_utf8_utf16<char16_t>, char16_t >{}.to_bytes(str16); }
 
std::u32string to_utf32( std::string str )
{ return std::wstring_convert< std::codecvt_utf8<char32_t>, char32_t >{}.from_bytes(str); }
 
std::string to_utf8( std::u32string str32 )
{ return std::wstring_convert< std::codecvt_utf8<char32_t>, char32_t >{}.to_bytes(str32); }
 
std::wstring to_wchar_t( std::string str )
{ return std::wstring_convert< std::codecvt_utf8<wchar_t>, wchar_t >{}.from_bytes(str); }
 
std::string to_utf8( std::wstring wstr )
{ return std::wstring_convert< std::codecvt_utf8<wchar_t>, wchar_t >{}.to_bytes(wstr); }

int main(void)
{
	wstring wstr = L"Hello World";
	string str = to_utf8(wstr);	
	cout << str << endl;
	
	u16string u16 = u"Hello World";
	str = to_utf8(u16);
	cout << str << endl;

	u32string u32 = U"Hello World";
	str = to_utf8(u32);
	cout << str << endl;

	return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *