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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚坏叔叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值