不管什么项目,或多或少都会遇到那么一点点转码的问题,
本片就提供两个实现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;
}
结果:
版权声明:本文为r5014原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。