下面贴个写的很简洁高效的类
CharacterEncoding.h
#pragma once
#include <string>
#include <Windows.h>
using namespace std;
class CharacterEncoding
{
public:
CharacterEncoding(void);
~CharacterEncoding(void);
void unicodeToUTF8( const wstring & src, string & result);
void unicodeToGB2312( const wstring & wstr , string & result);
void utf8ToUnicode( const string & src, wstring & result);
void gb2312ToUnicode( const string & src, wstring & result);
string gb2312ToUTF8(const string src);
string utf8ToGB2312(const string src);
};
CharacterEncoding.cpp
#include "CharacterEncoding.h"
CharacterEncoding::CharacterEncoding(void)
{
}
CharacterEncoding::~CharacterEncoding(void)
{
}
void CharacterEncoding::unicodeToUTF8( const wstring & src, string & result )
{
int n = WideCharToMultiByte( CP_UTF8, 0 , src.c_str(), - 1 , 0 , 0 , 0 , 0 );
result.resize(n);
::WideCharToMultiByte( CP_UTF8, 0 , src.c_str(), - 1 , ( char * )result.c_str(), result.length(), 0 , 0 );
}
void CharacterEncoding::unicodeToGB2312( const wstring & wstr , string & result )
{
int n = WideCharToMultiByte( CP_ACP, 0 , wstr.c_str(), - 1 , 0 , 0 , 0 , 0 );
result.resize(n);
::WideCharToMultiByte(CP_ACP, 0 , wstr.c_str(), - 1 , ( char * )result.c_str(), n, 0 , 0 );
}
void CharacterEncoding::utf8ToUnicode( const string & src, wstring & result )
{
int n = MultiByteToWideChar( CP_UTF8, 0 , src.c_str(), - 1 , NULL, 0 );
result.resize(n);
::MultiByteToWideChar( CP_UTF8, 0 , src.c_str(), - 1 , (LPWSTR)result.c_str(), result.length());
}
void CharacterEncoding::gb2312ToUnicode( const string & src, wstring & result )
{
int n = MultiByteToWideChar( CP_ACP, 0 , src.c_str(), - 1 , NULL, 0 );
result.resize(n);
::MultiByteToWideChar( CP_ACP, 0 , src.c_str(), - 1 , (LPWSTR)result.c_str(), result.length());
}
std::string CharacterEncoding::gb2312ToUTF8( const string src )
{
wstring temp;
gb2312ToUnicode(src,temp);
string ret;
unicodeToUTF8(temp,ret);
return ret;
}
std::string CharacterEncoding::utf8ToGB2312( const string src )
{
wstring temp;
utf8ToUnicode(src,temp);
string ret;
unicodeToGB2312(temp,ret);
return ret;
}
简单明了,对不