1、转UTF8编码
string StdStringToUTF8(const string& str){int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴ZeroMemory(pwBuf, nwLen * 2 + 2);::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);char * pBuf = new char[nLen + 1];ZeroMemory(pBuf, nLen + 1);::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);std::string retStr(pBuf);delete[]pwBuf;delete[]pBuf;pwBuf = NULL;pBuf = NULL;return retStr;}
2、转GBK编码
string StdStringToGBK(const string& str){int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴memset(pwBuf, 0, nwLen * 2 + 2);MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);char * pBuf = new char[nLen + 1];memset(pBuf, 0, nLen + 1);WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);std::string retStr = pBuf;delete[]pBuf;delete[]pwBuf;pBuf = NULL;pwBuf = NULL;return retStr;}
Qt中UTF8与GBK相互转换方法相对比较简单:
QString GBK2UTF8(const QString &str){QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");return utf8->toUnicode(str.toUtf8());}QString UTF82GBK(const QString &str){QTextCodec *gbk = QTextCodec::codecForName("GB18030");return gbk->toUnicode(str.toLocal8Bit());}std::string GBK2UTF8(std::string &str){QString temp = QString::fromLocal8Bit(str.c_str());std::string ret = temp.toUtf8().data();return ret;}std::string UTF82GBK(std::string &str){QString temp = QString::fromUtf8(str.c_str());std::string ret = temp.toLocal8Bit().data();return ret;}
如果觉得《String字符串编码格式转换(UTF8/GBK)》对你有帮助,请点赞、收藏,并留下你的观点哦!