C++ Unicode和ANSII转换
生活随笔
收集整理的這篇文章主要介紹了
C++ Unicode和ANSII转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
構造字符串和轉換字符串是不一樣的,構造字符串時往往是添加標記,這個過程其實是告訴編譯器應該怎么在內存中存儲;一旦構造好,對于內存中的一塊地址,這些標記符就沒用了,這個時候就得使用轉換函數轉換了。對于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的其他庫
總結
以上是生活随笔為你收集整理的C++ Unicode和ANSII转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2010发布、打包安装程序超全超详细
- 下一篇: 在VC中使用MATLAB C++函数库