C++ string互轉wstring/Unicode互轉ANSI/Unicode互轉UTF8

std::string StringConvUtil::UnicodeToANSI(const std::wstring& str)
{
	char*  pElementText;
	int    iTextLen;
	// 寬字節轉多字節
	iTextLen = WideCharToMultiByte(CP_ACP, 0,
		str.c_str(),
		-1,
		nullptr,
		0,
		nullptr,
		nullptr);

	pElementText = new char[iTextLen + 1];
	memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
	::WideCharToMultiByte(CP_ACP,
		0,
		str.c_str(),
		-1,
		pElementText,
		iTextLen,
		nullptr,
		nullptr);

	std::string strText;
	strText = pElementText;
	delete[] pElementText;
	return strText;
}

std::wstring StringConvUtil::AnsiToUNICODE(const std::string& str)
{
	wchar_t*  pElementText;
	int    iTextLen;
	// 寬字節轉多字節
	iTextLen = MultiByteToWideChar(CP_ACP, 0,
		str.c_str(),
		-1,
		nullptr,
		0);

	pElementText = new wchar_t[iTextLen + 1];
	memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
	::MultiByteToWideChar(CP_ACP,
		0,
		str.c_str(),
		-1,
		pElementText,
		iTextLen);

	std::wstring strText;
	strText = pElementText;
	delete[] pElementText;
	return strText;
}

std::string StringConvUtil::UnicodeToUTF8(LPCWSTR lpszWideStr)
{
	int nLen = ::WideCharToMultiByte(CP_UTF8, 0, lpszWideStr, -1,
		nullptr, 0, nullptr, nullptr);

	char* buffer = new char[nLen + 1];
	::ZeroMemory(buffer, nLen + 1);

	::WideCharToMultiByte(CP_UTF8, 0, lpszWideStr, -1,
		buffer, nLen, nullptr, nullptr);

	std::string multStr = buffer;
	delete[] buffer;
	return multStr;
}

std::wstring StringConvUtil::Utf8ToUnicode(const std::string& str)
{
	int nLen = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(),
		nullptr, 0);

	WCHAR* buffer = new WCHAR[nLen + 1];
	::ZeroMemory(buffer, sizeof(WCHAR)* (nLen + 1));

	::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(),
		buffer, nLen);

	std::wstring wideStr = buffer;
	delete[] buffer;
	return wideStr;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章