windows下C++实现Unicode和Utf8编码的互转

不管什么项目,或多或少都会遇到那么一点点转码的问题,

本片就提供两个实现Unicode和UTF8互转的函数。

环境为WINDOW 10, VS2010

(该函数在Windows下,也使用了windows的函数,如果使用通用的函数那么请使用C的库“mbstowcs()/wcstombs()”我还是觉得直接用系统的比较方便)
 

1.UNICODE转UTF8

#include <iostream>
#include <windows.h>
#include <wchar.h>

/*
* 从宽字符串转为utf8字符串
* @param [in] in_wStr 输入宽字符串
* @return 返回值为UTF8字符串,如果转换失败,返回NULL
*/		
std::string UnicodeToUtf8(const std::wstring& in_wStr)
{
	int nNeedChars = WideCharToMultiByte( CP_UTF8, 0, in_wStr.c_str(), -1, 0, 0, 0, 0 );
	if (nNeedChars > 0)//再次判断一下
	{	
		std::vector<char> temp(nNeedChars);
		::WideCharToMultiByte( CP_UTF8, 0, in_wStr.c_str(), -1, &temp[0], nNeedChars, 0, 0 );
		return std::string(&temp[0]);
	}

	return std::string();
}

2.UTF8转为UNICODE

#include <iostream>
#include <windows.h>
#include <wchar.h>

/*
* 从utf8字符串转为宽字符串
* @param [in] in_utf8Str 输入UTF8字符串
* @return 返回值为UNICODE字符串,如果转换失败,返回NULL
*/
std::wstring Utf8ToUnicode(const std::string& in_utf8Str)
{
	int nNeedWchars = MultiByteToWideChar( CP_UTF8, 0, in_utf8Str.c_str(), -1, NULL, 0 );
	if (nNeedWchars > 0)
	{
		std::vector<wchar_t> temp(nNeedWchars);
		::MultiByteToWideChar( CP_UTF8, 0, in_utf8Str.c_str(), -1, &temp[0], nNeedWchars );
		return std::wstring(&temp[0]);
	}

	return std::wstring();
}

示例:


int main(int argc, char *argv[])
{

	std::string ascii_string = "这是一条utf8字符串";
	std::string utf8_string;
	std::string utf8_to_ascii_string;
	std::wstring utf8_to_unicode_string;
	std::string unicode_to_utf8_string;
	std::string unicode_to_ascii_string;

	utf8_string = AsciiToUtf8(ascii_string);
	utf8_to_ascii_string = Utf8ToAscii(utf8_string);
	utf8_to_unicode_string = Utf8ToUnicode(utf8_string);
	unicode_to_utf8_string = UnicodeToUtf8(utf8_to_unicode_string);
	unicode_to_ascii_string = UnicodeToAscii(utf8_to_unicode_string);

	std::cout  << "ascii_string           "  << ascii_string            << std::endl;
	std::cout  << "utf8_string           "  << utf8_string            << std::endl;
	std::cout  << "utf8_to_ascii_string  "  << utf8_to_ascii_string   << std::endl;
	std::wcout << L"utf8_to_unicode_string" << utf8_to_unicode_string << std::endl;
	std::cout  << "unicode_to_utf8_string"  << unicode_to_utf8_string << std::endl;
	std::cout  << "unicode_to_ascii_string"  << unicode_to_ascii_string << std::endl;

	return 0;
}

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值