GBK转UTF8编码-UTF8转GBK编码(C++)
版本一:string,GBK转UTF8,UTF8转GBK
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> #include "tchar.h" #include <string> #include <windows.h> using namespace std; string GBKToUTF8(const std::string & strGBK) { string strOutUTF8 = ""; WCHAR * str1; int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0); str1 = new WCHAR[n]; MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n); n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL); char * str2 = new char[n]; WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL); strOutUTF8 = str2; delete[]str1; str1 = NULL; delete[]str2; str2 = NULL; return strOutUTF8; } string UTF8ToGBK(const std::string & strUTF8) { int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0); unsigned short * wszGBK = new unsigned short[len + 1]; memset(wszGBK, 0, len * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUTF8.c_str(), -1, wszGBK, len); len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL); char *szGBK = new char[len + 1]; memset(szGBK, 0, len + 1); WideCharToMultiByte(CP_ACP,0, wszGBK, -1, szGBK, len, NULL, NULL); //strUTF8 = szGBK; std::string strTemp(szGBK); delete[]szGBK; delete[]wszGBK; return strTemp; } int _tmain(int argc, _TCHAR * argv[]) { string test = "C/C++程序员之家 - 关注cplusplus,关注互联网,关注路由与交换.程序员的历程."; cout<<test<<endl; cout<<GBKToUTF8(test)<<endl; //转为UTF8 cout<<UTF8ToGBK(GBKToUTF8(test))<<endl; //转为UTF8再转为GBK return 0; } |
版本二:CString,GBK转UTF8,UTF8转GBK
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
CString UTF8ToGB(CString & str) { CString szOut; WCHAR *strSrc; TCHAR *szRes; int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); strSrc = new WCHAR[i+1]; MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i); i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL); szRes = new TCHAR[i+1]; WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL); szOut = szRes; delete []strSrc; delete []szRes; return szOut; } CString GBKToUTF8(CString & strGBK) { CString strOutUTF8 = ""; WCHAR * str1; int n = MultiByteToWideChar(CP_ACP, 0, strGBK, -1, NULL, 0); str1 = new WCHAR[n]; MultiByteToWideChar(CP_ACP, 0, strGBK, -1, str1, n); n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL); char * str2 = new char[n]; WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL); strOutUTF8 = str2; delete[]str1; str1 = NULL; delete[]str2; str2 = NULL; return strOutUTF8; } |
Copyright:cpp.cloudcpp.com Share、Open- C/C++程序员之家
One Reply to “GBK转UTF8编码-UTF8转GBK编码(C++)”
感觉C++,和JAVA代码有点相似。。。