700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > String字符串编码格式转换(UTF8/GBK)

String字符串编码格式转换(UTF8/GBK)

时间:2020-07-04 12:45:26

相关推荐

String字符串编码格式转换(UTF8/GBK)

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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。