您的位置:首页 > 编程语言 > C语言/C++

【原创】 VC++各种字符串类型转换

2013-04-16 16:58 399 查看
包括VC编程时常用的Unicode和Char互转,CString和std::string互转, 其他的转换可以由这个几个转化间接得到

// convert.h

#include <string>

#ifndef  _CONVERT_H_
#define  _CONVERT_H_

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

static int Ansi2Unicode(__in const char* pSrc,  wchar_t *pDst, __in size_t nChsOfDst);

static int Unicode2Ansi(__in const wchar_t * pSrc, char* pDst, __in size_t nBytesOfDst);

static std::string CString2String(CString str);

static CString String2CString(const std::string& str);
};

#endif


//convert.cpp

#include "StdAfx.h"
#include "Convert.h"

CConvert::CConvert(void)
{
}

CConvert::~CConvert(void)
{
}

int CConvert::Ansi2Unicode(__in const char* pSrc,  wchar_t *pDst, __in size_t nChsOfDst)
{
if (NULL == pDst)
{
int nChsOfDstNeed = MultiByteToWideChar(CP_ACP, 0, pSrc, -1, NULL, 0); //unicdoe缓冲区需要的字符数,包括\0;
return nChsOfDstNeed;
}

return MultiByteToWideChar(CP_ACP, 0, pSrc, -1, pDst, nChsOfDst);
}

int CConvert::Unicode2Ansi(__in const wchar_t * pSrc, char* pDst, __in size_t nBytesOfDst)
{
if (NULL == pDst)
{
int nBytesOfDstNeed = WideCharToMultiByte(CP_ACP, 0, pSrc, -1, NULL, 0, NULL, NULL); //返回需要写的字节数,包括末尾的\0;
return nBytesOfDstNeed;
}

return WideCharToMultiByte(CP_ACP, 0, pSrc, -1, pDst, nBytesOfDst, NULL, NULL); //返回需要写的字节数,包括末尾的\0;
}

std::string CConvert::CString2String(CString str)
{
int len = str.GetLength();
TCHAR* pSrc = str.GetBuffer(len);

if (NULL == pSrc)
{
return NULL;
}

int nBytesOfDst = Unicode2Ansi(pSrc, NULL, 0);
if (0 == nBytesOfDst)
{
return NULL;
}

char *pDst = new char[nBytesOfDst / sizeof(char)];
memset(pDst, 0, nBytesOfDst);

Unicode2Ansi(pSrc, pDst, nBytesOfDst);

std::string strRet(pDst);
delete[] pDst;

return strRet;
}

CString CConvert::String2CString(const std::string& str)
{
CString strRet(str.c_str());

return strRet;
}


//使用代码实例

void CMFCMacrosDlg::Ansi2Unicode()
{
CConvert obj;

char* pSrc = "cuihao";
int nChsOfDst = obj.Ansi2Unicode(pSrc, NULL, 0);
wchar_t *pDst = new wchar_t[nChsOfDst];
nChsOfDst = obj.Ansi2Unicode(pSrc, pDst, nChsOfDst);

MessageBox(CString(pDst));

delete[] pDst;
}

void CMFCMacrosDlg::Unicode2Ansi()
{
// TODO: 在此添加控件通知处理程序代码;
CConvert obj;

wchar_t *pSrc = L"cuihao";

int nBytesOfDst = obj.Unicode2Ansi(pSrc, NULL, 0);

char *pDst = new char[nBytesOfDst / sizeof(char)];  //包含\0

obj.Unicode2Ansi(pSrc, pDst, nBytesOfDst);

MessageBox(CString(pDst));

delete[] pDst;
}

void CMFCMacrosDlg::CString2String()
{
// TODO: 在此添加控件通知处理程序代码;

CString str("cuihao");

CConvert obj;

std::string strInfo = obj.CString2String(str);

MessageBox(obj.String2CString(strInfo));
}

void CMFCMacrosDlg::String2CString()
{
std::string str("cuihao");

CConvert obj;
CString strRet = obj.String2CString(str);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: