C++ Unicode和ANSII转换
生活随笔
收集整理的這篇文章主要介紹了
C++ Unicode和ANSII转换
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
構(gòu)造字符串和轉(zhuǎn)換字符串是不一樣的,構(gòu)造字符串時(shí)往往是添加標(biāo)記,這個過程其實(shí)是告訴編譯器應(yīng)該怎么在內(nèi)存中存儲;一旦構(gòu)造好,對于內(nèi)存中的一塊地址,這些標(biāo)記符就沒用了,這個時(shí)候就得使用轉(zhuǎn)換函數(shù)轉(zhuǎn)換了。對于C#、JAVA等語言都有Encode類,C++的庫就沒有那么豐富了,下面簡單介紹C++比較常用的幾種辦法:
一、直接利用std::string和std::wstring的轉(zhuǎn)換
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字符串映射到一個多字節(jié)字符串
WideCharToMultiByte的代碼頁用來標(biāo)記與新轉(zhuǎn)換的字符串相關(guān)的代碼頁。
MultiByteToWideChar的代碼頁用來標(biāo)記與一個多字節(jié)字符串相關(guān)的代碼頁。
常用的代碼頁由CP_ACP和CP_UTF8兩個。
使用CP_ACP代碼頁就實(shí)現(xiàn)了ANSI與Unicode之間的轉(zhuǎn)換。
使用CP_UTF8代碼頁就實(shí)現(xiàn)了UTF-8與Unicode之間的轉(zhuǎn)換。
下面是代碼實(shí)現(xiàn):
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的其他庫
總結(jié)
以上是生活随笔為你收集整理的C++ Unicode和ANSII转换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2010发布、打包安装程序超全超详细
- 下一篇: 在VC中使用MATLAB C++函数库