C/C++实现字符串的UTF-8/ANSI/Unicode的相互转换
约 287 字小于 1 分钟...
摘要
本文提供了一种使用C/C++在Windows平台对字符串进行UTF-8/ANSI/Unicode相互转换的方法:
源码
// ANSI -> Unicode
LPWSTR string::A2W(CONST LPCSTR a) {
CONST AUTO len = MultiByteToWideChar(CP_ACP, 0, a, static_cast<INT>(strlen(a)), nullptr, 0);
CONST AUTO w = new WCHAR[len + 1];
MultiByteToWideChar(CP_ACP, 0, a, static_cast<INT>(strlen(a)), w, len);
w[len] = '\0';
return w;
}
// Unicode -> ANSI
LPSTR string::W2A(CONST LPCWSTR w) {
CONST AUTO len = WideCharToMultiByte(CP_ACP, 0, w, static_cast<INT>(wcslen(w)), nullptr, 0, nullptr, nullptr);
CONST AUTO a = new CHAR[len + 1];
WideCharToMultiByte(CP_ACP, 0, w, static_cast<INT>(wcslen(w)), a, len, nullptr, nullptr);
a[len] = '\0';
return a;
}
// UTF-8 -> ANSI
std::string string::U2A(CONST std::string& utf8) {
CONST AUTO wlen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0);
CONST AUTO wbuf = new WCHAR[wlen];
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, wbuf, wlen);
CONST AUTO len = WideCharToMultiByte(CP_ACP, 0, wbuf, -1, nullptr, 0, nullptr, nullptr);
CONST AUTO buf = new CHAR[len];
WideCharToMultiByte(CP_ACP, 0, wbuf, -1, buf, len, nullptr, nullptr);
std::string result(buf);
delete[] wbuf;
delete[] buf;
return result;
}
Powered by Waline v3.3.0