字符串编码转换封装函数,UTF-8编码与本地编码互转。
有时候我们会遇到乱码的字符串,比如:
Utf8ToLocal(string str)
函数转换一下就可以了。LocalToUtf8(string str)
函数转换一下能搞定。//将UTF-8编码的字符串转换为本地编码
string Utf8ToLocal(string str)
{
std::string result;
WCHAR* strSrc;
LPSTR szRes;
//获得临时变量的大小
int i = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
strSrc = new WCHAR[i + 1];
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, strSrc, i);
//获得临时变量的大小
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new CHAR[i + 1];
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
delete[]strSrc;
delete[]szRes;
return result;
}
//将本地编码转换为UTF-8编码的字符串
string LocalToUtf8(string str)
{
std::string result;
WCHAR* strSrc;
CHAR* szRes;
int i;
// 获得临时变量的大小
i = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
strSrc = new WCHAR[i + 1];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, strSrc, i);
// 获得临时变量的大小
i = WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new CHAR[i + 1];
WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
delete[] strSrc;
delete[] szRes;
return result;
}