简介在C++开发过程中,最常见的就是字符编码之间相互转换。主要有Unicode转ANSI、Unicode转UTF8、ANSI转Unicode、UTF8转Unicode、ANSI转UTF8等等。

编写一个字符编码帮助类

// 字符编码帮助类
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#include "..\stdafx.h"

#include <string>
#include <iostream>
using namespace std;

class CCharHelper
{
public:
	CCharHelper(void);
	virtual ~CCharHelper(void);

	static string UnicodeToANSI(const wstring& str);
	static wstring UTF8ToUnicode(const string& str);
	static wstring ANSIToUnicode(const string& str);
	static string UnicodeToUTF8(const wstring& str);
	static string ANSIToUTF8(const char* ansi);
};

Unicode转ANSI

string CCharHelper::UnicodeToANSI(const wstring& str)
{
	char*     pElementText;
	int    iTextLen;
	// wide char to multi char
	iTextLen = WideCharToMultiByte(CP_ACP,
		0,
		str.c_str(),
		-1,
		NULL,
		0,
		NULL,
		NULL);
	pElementText = new char[iTextLen + 1];
	memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
	::WideCharToMultiByte(CP_ACP,
		0,
		str.c_str(),
		-1,
		pElementText,
		iTextLen,
		NULL,
		NULL);
	string strText;
	strText = pElementText;
	delete[] pElementText;
	return strText;
}

Unicode转UTF8

string CCharHelper::UnicodeToUTF8(const wstring& str)
{
	char*     pElementText;
	int    iTextLen;
	// wide char to multi char
	iTextLen = WideCharToMultiByte(CP_UTF8,
		0,
		str.c_str(),
		-1,
		NULL,
		0,
		NULL,
		NULL);
	pElementText = new char[iTextLen + 1];
	memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
	::WideCharToMultiByte(CP_UTF8,
		0,
		str.c_str(),
		-1,
		pElementText,
		iTextLen,
		NULL,
		NULL);
	string strText;
	strText = pElementText;
	delete[] pElementText;
	return strText;
}

ANSI转Unicode

wstring CCharHelper::ANSIToUnicode(const string& str)
{
	int  len = 0;
	len = str.length();
	int  unicodeLen = ::MultiByteToWideChar(CP_ACP,
		0,
		str.c_str(),
		-1,
		NULL,
		0);
	wchar_t *  pUnicode;
	pUnicode = new  wchar_t[unicodeLen + 1];
	memset(pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));
	::MultiByteToWideChar(CP_ACP,
		0,
		str.c_str(),
		-1,
		(LPWSTR)pUnicode,
		unicodeLen);
	wstring  rt;
	rt = (wchar_t*)pUnicode;
	delete  pUnicode;

	return  rt;
}

UTF8转Unicode

wstring CCharHelper::UTF8ToUnicode(const string& str)
{
	int  len = 0;
	len = str.length();
	int  unicodeLen = ::MultiByteToWideChar(CP_UTF8,
		0,
		str.c_str(),
		-1,
		NULL,
		0);
	wchar_t *  pUnicode;
	pUnicode = new  wchar_t[unicodeLen + 1];
	memset(pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));
	::MultiByteToWideChar(CP_UTF8,
		0,
		str.c_str(),
		-1,
		(LPWSTR)pUnicode,
		unicodeLen);
	wstring  rt;
	rt = (wchar_t*)pUnicode;
	delete  pUnicode;

	return  rt;
}

ANSI转UTF8

std::string CCharHelper::ANSIToUTF8(const char* ansi)
{
	if (ansi == NULL) {
		return "";
	}
	std::wstring unicode_str = CCharHelper::ANSIToUnicode(ansi);
	return CCharHelper::UnicodeToUTF8(unicode_str.c_str());
}


源码下载
  • 最近更新:   2022-06-17开发环境:   Visual Studio 2015
  • 源码大小:   1.83KB下载次数:  26 

更多为你推荐