VC++中使⽤std::string转换字符串编码
⽬录
第1章说明
VC++中宽窄字符串的相互转换⽐较⿇烦,借助std::string能⼤⼤减少代码量。
1.1 代码
函数声明如下:
std::string stringA2W(const char* pA,int nA,UINT uCodePage =CP_ACP);
std::string stringW2A(const wchar_t*pW,int nW,UINT uCodePage =CP_ACP);
std::string stringA2W(const std::string&sA,UINT uCodePage = CP_ACP);std::string stringW2A(const CP_ACP);函数实现如下:
/***************************************************************\\窄字符串 ==> 宽字符串(UTF16LE)pA [in] 窄字符串⾸地址
nA [in] 窄字符串长度。⼩于零就使⽤ strlen 计算长度。uCodePage [in] 窄字符串的代码页
如:CP_ACP 表⽰系统默认;936 表⽰ GBK……返回:宽字符串 sW
宽字符串的字符数 nChar = sW.length() / sizeof(wchar_t)宽字符串的字节数 nByte = (nChar + 1) * sizeof(wchar_t) - 1字节数多加了 sizeof(wchar_t) - 1 = 1 个 \\0,是为了下⾯的⽤法const wchar_t* pW = (const wchar_t*)sW.c_str();\\***************************************************************/std::string stringA2W(const char*pA,int nA,UINT uCodePage){
std::string sW;if(pA){if(nA < 0){
nA = strlen(pA);}if(nA > 0)
std::string&sW,UINT
uCodePage
=
if(nA > 0){
int nW = MultiByteToWideChar(uCodePage,0,pA,nA,NULL,0);if(nW > 0){
int nByte = (nW + 1) * sizeof(wchar_t);wchar_t*pW = (wchar_t*)malloc(nByte);if(pW){
MultiByteToWideChar(uCodePage,0,pA,nA,pW,nW);pW[nW] = L'\\0';
sW.assign((const char*)pW,nByte - 1);free(pW);}}}}
if(sW.empty()){
sW = std::string(sizeof(wchar_t) - 1,'\\0');}
return sW;}
/***************************************************************\\窄字符串 ==> 宽字符串(UTF16LE)sA [in] 窄字符串
uCodePage [in] 窄字符串的代码页
如:CP_ACP 表⽰系统默认;936 表⽰ GBK……返回:宽字符串
\\***************************************************************/std::string stringA2W(const std::string&sA,UINT uCodePage){
return stringA2W(sA.c_str(),sA.length(),uCodePage);}
/***************************************************************\\宽字符串(UTF16LE) ==> 窄字符串pW [in] 宽字符串⾸地址
nW [in] 宽字符串字符数。⼩于零就使⽤ wcslen 计算长度。uCodePage [in] 窄字符串的代码页
如:CP_ACP 表⽰系统默认;936 表⽰ GBK……返回:窄字符串
\\***************************************************************/
std::string stringW2A(const wchar_t*pW,int nW,UINT uCodePage){
std::string sA;if(pW){if(nW < 0){
nW = wcslen(pW);}if(nW > 0){
int nA = WideCharToMultiByte(uCodePage,0,pW,nW,NULL,NULL,NULL,NULL);if(nA > 0){
char*pA = (char*)malloc(nA);if(pA){
WideCharToMultiByte(uCodePage,0,pW,nW,pA,nA,NULL,NULL);sA.assign(pA,nA);free(pA);}}}}return sA;}
/***************************************************************\\宽字符串(UTF16LE) ==> 窄字符串sW [in] 宽字符串,编码为 UTF16LEuCodePage [in] 窄字符串的代码页
如:CP_ACP 表⽰系统默认;936 表⽰ GBK……返回:窄字符串
\\***************************************************************/
std::string stringW2A(const std::string&sW,UINT uCodePage){
return stringW2A((const wchar_t*)sW.c_str(),sW.length() / sizeof(wchar_t),uCodePage);}
1.2 使⽤
有了上述四个函数,字符串的编码转换⽤⼀、两⾏代码即可实现。如:将GBK字符串\"测试\"转换为宽字符串std::string sW = stringA2W(\"测试\");std::string sW = stringA2W(\"测试\
//简体中⽂ Windows 下
//安装有代码页936的Windows
如:将GBK字符串\"测试\"转换为UTF-8编码
std::string sUTF8 = stringW2A(stringA2W(\"测试\如:将GBK字符串\"测试\"转换为Big5编码
std::string sBig5 = stringW2A(stringA2W(\"测试\