日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ Unicode和ANSII转换

發布時間:2023/12/2 c/c++ 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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转换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。