构造字符串和转换字符串是不一样的,构造字符串时往往是添加标记,这个过程其实是告诉编译器应该怎么在内存中存储;一旦构造好,对于内存中的一块地址,这些标记符就没用了,这个时候就得使用转换函数转换了。对于C#、JAVA等语言都有Encode类,C++的库就没有那么丰富了,下面简单介绍C++比较常用的几种办法:
一、直接利用std::string和std::wstring的转换
std::string str = "I'm a string"
std::wstring wstr(str.begin(), str.end());std::wstring wstr = "I'm a wstring"
std::string str(wstr.begin(), wstr.end());
二、WideCharToMultiByte将unicode字符串映射到一个多字节字符串
WideCharToMultiByte的代码页用来标记与新转换的字符串相关的代码页。
MultiByteToWideChar的代码页用来标记与一个多字节字符串相关的代码页。
常用的代码页由CP_ACP和CP_UTF8两个。
使用CP_ACP代码页就实现了ANSI与Unicode之间的转换。
使用CP_UTF8代码页就实现了UTF-8与Unicode之间的转换。
下面是代码实现:
1. ANSI to Unicode
wstring ANSIToUnicode( const string& str )
{int len = 0;len = str.length();int unicodeLen = ::MultiByteToWideChar( CP_ACP,0,str.c_str(),-1,NULL,0 ); wchar_t * pUnicode; pUnicode = new wchar_t[unicodeLen+1]; memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t)); ::MultiByteToWideChar( CP_ACP,0,str.c_str(),-1,(LPWSTR)pUnicode,unicodeLen ); wstring rt; rt = ( wchar_t* )pUnicode;delete pUnicode; return rt;
}
2. Unicode to ANSI
string UnicodeToANSI( const wstring& str )
{char* pElementText;int iTextLen;// wide char to multi chariTextLen = WideCharToMultiByte( CP_ACP,0,str.c_str(),-1,NULL,0,
NULL,NULL );pElementText = new char[iTextLen + 1];memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );::WideCharToMultiByte( CP_ACP,0,str.c_str(),-1,pElementText,iTextLen,NULL,NULL );string strText;strText = pElementText;delete[] pElementText;return strText;
}
3. UTF-8 to Unicode
wstring UTF8ToUnicode( const string& str )
{int len = 0;len = str.length();int unicodeLen = ::MultiByteToWideChar( CP_UTF8,0,str.c_str(),-1,NULL,0 ); wchar_t * pUnicode; pUnicode = new wchar_t[unicodeLen+1]; memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t)); ::MultiByteToWideChar( CP_UTF8,0,str.c_str(),-1,(LPWSTR)pUnicode,unicodeLen ); wstring rt; rt = ( wchar_t* )pUnicode;delete pUnicode; return rt;
}
4. Unicode to UTF-8
string UnicodeToUTF8( const wstring& str )
{char* pElementText;int iTextLen;// wide char to multi chariTextLen = WideCharToMultiByte( CP_UTF8,0,str.c_str(),-1,NULL,0,NULL,NULL );pElementText = new char[iTextLen + 1];memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );::WideCharToMultiByte( CP_UTF8,0,str.c_str(),-1,pElementText,iTextLen,NULL,NULL );string strText;strText = pElementText;delete[] pElementText;return strText;
}
三、使用MS的其他库