在学习的时候,宽字节和多字节直接的转换经常会用到,还会用到CString\ LPWSTR\TCHAR CHAR\LPSTR,所以就自己写了一个类。方便自己使用。
MyChar.h文件
/************************************************************************/
/* wchar_t与char类型间的转换
/* CString\ LPWSTR\TCHAR CHAR\LPSTR之间间的转换
/************************************************************************/
class CMyChar
{
public:
CMyChar();
~CMyChar();
public:
char* WcharToChar(wchar_t* wcStr);//宽字节转单字节
wchar_t* CharToWchar(char* cStr); //单字节转宽字节
void Release();//释放资源
private:
char* m_char;
wchar_t* m_wchar;
};
MyChar.cpp
文件
#include "stdafx.h"
#include "MyChar.h"
#include <windows.h>
CMyChar::CMyChar()
:m_char(NULL)
, m_wchar(NULL)
{
}
CMyChar::~CMyChar()
{
Release();
}
/************************************************************************/
/*字符类型 wchar_t char
/*获取字符长度 wcslen() strlen()
/*连接两个字符串 wcscat() strcpy()
/*复制字符串 wcscpy() strcpy()
/*比较两个字符串 wcscmp() strcmp()
/************************************************************************/
char* CMyChar::WcharToChar(wchar_t* wcStr)
{
Release();
int len = WideCharToMultiByte(CP_ACP, 0, wcStr, wcslen(wcStr), NULL, 0, NULL, NULL);
m_char = new char[len + 1];
WideCharToMultiByte(CP_ACP, 0, wcStr, wcslen(wcStr), m_char, len, NULL, NULL);
m_char[len] = '\0';
return m_char;
}
wchar_t* CMyChar::CharToWchar(char* cStr)
{
Release();
int len = MultiByteToWideChar(CP_ACP, 0, cStr, strlen(cStr), NULL, 0);
m_wchar = new wchar_t[len + 1];
MultiByteToWideChar(CP_ACP, 0, cStr, strlen(cStr), m_wchar, len);
m_wchar[len] = '\0';
return m_wchar;
}
void CMyChar::Release()
{
if (m_char)
{
delete m_char;
m_char = NULL;
}
if (m_wchar)
{
delete m_wchar;
m_wchar = NULL;
}
}
#include "stdafx.h"
#include "MyChar.h"
#include <wtypes.h>
int _tmain(int argc, _TCHAR* argv[])
{
WCHAR* wc = L"进行测试";
CMyChar u;
char* c = u.WcharToChar(wc);
printf("%s\n", c);
char* c2 = "abcd";
WCHAR* wc2 = u.CharToWchar(c2);
//cout << *wc2 << endl;
wprintf(L"%s", wc2);
return 0;
}