C/C++ implementation of mutual conversion between UTF-8/ANSI/Unicode strings
About 263 wordsLess than 1 minute...
Abstract
This article provides a method for converting strings between UTF-8/ANSI/Unicode using C/C++ on the Windows platform:
Source code
// 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