文章详情
C++文本转换(utf8与ansi编码互转)
Posted on 2019-11-06 20:03:10 by 主打一个C++
//Utf8转Ansi编码
std::string Utf8ToAnsi(const std::string& utf8Str) {
// 计算需要的缓冲区大小
int size = MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, NULL, 0);
// 创建一个宽字符缓冲区
std::wstring wideStr(size, L'\0');
// 将 UTF-8 转换为宽字符
MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, &wideStr[0], size);
// 计算新的 ANSI 字符串大小
size = WideCharToMultiByte(GetACP(), 0, wideStr.c_str(), -1, NULL, 0, NULL, NULL);
// 创建 ANSI 字符串缓冲区
std::string ansiStr(size, '\0');
// 将宽字符转换为 ANSI
WideCharToMultiByte(GetACP(), 0, wideStr.c_str(), -1, &ansiStr[0], size, NULL, NULL);
return ansiStr;
}
//Ansi编码转Utf8
std::string AnsiToUtf8(const std::string& ansiStr) {
// 计算需要的缓冲区大小
int size = MultiByteToWideChar(GetACP(), 0, ansiStr.c_str(), -1, NULL, 0);
// 创建一个宽字符缓冲区
std::wstring wideStr(size, L'\0');
// 将 ANSI 转换为宽字符
MultiByteToWideChar(GetACP(), 0, ansiStr.c_str(), -1, &wideStr[0], size);
// 计算新的 UTF-8 字符串大小
size = WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, NULL, 0, NULL, NULL);
// 创建 UTF-8 字符串缓冲区
std::string utf8Str(size, '\0');
// 将宽字符转换为 UTF-8
WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, &utf8Str[0], size, NULL, NULL);
return utf8Str;
}
*转载请注明出处:原文链接:https://cpp.vin/page/103.html