头文件:
#pragma once
#include <string>
class StrConvert
{
public:
StrConvert(void);
~StrConvert(void);
//static void Wchar_tToString(std::string& szDst, wchar_t *wchar);
static std::string Wchar_tToString(wchar_t *wchar);
//static void StringToWstring(std::wstring& szDst, std::string str);
static std::wstring StringToWstring(std::string str);
static char* WcharToChar(wchar_t* wc);
static wchar_t* CharToWchar(char* c);
};
源文件:
#include "StdAfx.h"
#include "StrConvert.h"
StrConvert::StrConvert(void)
{
}
StrConvert::~StrConvert(void)
{
}
//void StrConvert::Wchar_tToString(std::string& szDst, wchar_t *wchar)
//{
//wchar_t * wText = wchar;
//DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);// WideCharToMultiByte的运用
//char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量
//psText = new char[dwNum];
//WideCharToMultiByte (CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);// WideCharToMultiByte的再次运用
//szDst = psText;// std::string赋值
//delete []psText;// psText的清除
//}
std::string StrConvert::Wchar_tToString(wchar_t *wchar)
{
std::string szDst;
wchar_t * wText = wchar;
DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);// WideCharToMultiByte的运用
char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量
psText = new char[dwNum];
WideCharToMultiByte (CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);// WideCharToMultiByte的再次运用
szDst = psText;// std::string赋值
delete []psText;// psText的清除
return szDst;
}
//void StrConvert::StringToWstring(std::wstring& szDst, std::string str)
//{
//std::string temp = str;
//int len=MultiByteToWideChar(CP_ACP, 0, (LPCSTR)temp.c_str(), -1, NULL,0);
//wchar_t * wszUtf8 = new wchar_t[len+1];
//memset(wszUtf8, 0, len * 2 + 2);
//MultiByteToWideChar(CP_ACP, 0, (LPCSTR)temp.c_str(), -1, (LPWSTR)wszUtf8, len);
//szDst = wszUtf8;
//std::wstring r = wszUtf8;
//delete[] wszUtf8;
//}
std::wstring StrConvert::StringToWstring(std::string str)
{
std::wstring szDst;
std::string temp = str;
int len=MultiByteToWideChar(CP_ACP, 0, (LPCSTR)temp.c_str(), -1, NULL,0);
wchar_t * wszUtf8 = new wchar_t[len+1];
memset(wszUtf8, 0, len * 2 + 2);
MultiByteToWideChar(CP_ACP, 0, (LPCSTR)temp.c_str(), -1, (LPWSTR)wszUtf8, len);
szDst = wszUtf8;
std::wstring r = wszUtf8;
delete[] wszUtf8;
return szDst;
}
char* StrConvert::WcharToChar(wchar_t* wc)
{
char* m_char;
wchar_t* m_wchar;
int len= WideCharToMultiByte(CP_ACP,0,wc,wcslen(wc),NULL,0,NULL,NULL);
m_char=new char[len+1];
WideCharToMultiByte(CP_ACP,0,wc,wcslen(wc),m_char,len,NULL,NULL);
m_char[len]='\0';
return m_char;
}
//将char* 转成wchar_t*的实现函数如下:
//这是把asii字符转换为unicode字符,和上面相同的原理
wchar_t* StrConvert::CharToWchar(char* c)
{
char* m_char;
wchar_t* m_wchar;
int len = MultiByteToWideChar(CP_ACP,0,c,strlen(c),NULL,0);
m_wchar=new wchar_t[len+1];
MultiByteToWideChar(CP_ACP,0,c,strlen(c),m_wchar,len);
m_wchar[len]='\0';
return m_wchar;
}