标签:
最近在编程中经常遇到需要多字节字符与宽字节字符相互转换的问题,一直自己贴那几句代码。觉得麻烦,于是就自己写了一个类来封装wchar_t与char类型间的转换,
其他的,诸如:CString\ LPWSTR\TCHAR CHAR\LPSTR之间也是一样用
头文件:
#ifndef USE_H_ #define USE_H_ #include <iostream> #include <windows.h> #include <string> using namespace std;
//字符类型 wchar_t char
//获取字符长度 wcslen() strlen()
//连接两个字符串 wcscat() strcat()
//复制字符串 wcscpy() strcpy()
//比较两个字符串 wcscmp() strcmp()
//具体参数详见百度
class CUser { public: CUser(); virtual~ CUser(); char* WcharToChar(const wchar_t* wp); char* StringToChar(const string& s); char* WstringToChar(const wstring& ws); wchar_t* CharToWchar(const char* c); wchar_t* WstringToWchar(const wstring& ws); wchar_t* StringToWchar(const string& s); wstring StringToWstring(const string& s); string WstringToString(const wstring& ws); void Release(); private: char* m_char; wchar_t* m_wchar; }; #endif;
实现文件:
#include "stdafx.h" #include "use.h" CUser::CUser() :m_char(NULL) ,m_wchar(NULL) { } CUser::~CUser() { Release(); } char* CUser::WcharToChar(const wchar_t* wp) { Release(); int len= WideCharToMultiByte(CP_ACP,0,wp,wcslen(wp),NULL,0,NULL,NULL); m_char=new char[len+1]; WideCharToMultiByte(CP_ACP,0,wp,wcslen(wp),m_char,len,NULL,NULL); m_char[len]=‘\0‘; return m_char; } wchar_t* CUser::CharToWchar(const char* c) { Release(); 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; } void CUser::Release() {
if(m_char)
{
delete [] m_char;
m_char=NULL;
}
if(m_wchar)
{
delete [] m_wchar;
m_wchar=NULL;
}
} char* CUser::StringToChar(const string& s) { return const_cast<char*>(s.c_str()); } char* CUser::WstringToChar(const std::wstring &ws) { const wchar_t* wp=ws.c_str(); return WcharToChar(wp); } wchar_t* CUser::WstringToWchar(const std::wstring &ws) { return const_cast<wchar_t*>(ws.c_str()); } wchar_t* CUser::StringToWchar(const string& s) { const char* p=s.c_str(); return CharToWchar(p); } string CUser::WstringToString(const std::wstring &ws) { string s; char* p=WstringToChar(ws); s.append(p); return s; } wstring CUser::StringToWstring(const std::string &s) { wstring ws; wchar_t* wp=StringToWchar(s); ws.append(wp); return ws; }
如果涉及到CString,可以利用CString::GetBuffer()函数来进行转换,道理一样.
使用的时候非常简单了:
WCHAR* wc=findData.cFileName; CUser u; char* c=u.WcharToChar(wc);
c++中char*\wchar_t*\string\wstring之间的相互转换
标签:
原文地址:http://www.cnblogs.com/shouce/p/5062401.html