C++宽字符与普通字符的转换实例详解
C++宽字符与普通字符的转换实例详解
把字符串转换成宽字符串,
实例代码:
wstringstring2Wstring(stringsToMatch)
{
#ifdef_A_WIN
intiWLen=MultiByteToWideChar(CP_ACP,0,sToMatch.c_str(),sToMatch.size(),0,0);//计算转换后宽字符串的长度。(不包含字符串结束符)
wchar_t*lpwsz=newwchar_t[iWLen+1];
MultiByteToWideChar(CP_ACP,0,sToMatch.c_str(),sToMatch.size(),lpwsz,iWLen);//正式转换。
lpwsz[iWLen]=L'/0';
wstringwsToMatch(lpwsz);
delete[]lpwsz;
#elif_A_LINUX
setlocale(LC_CTYPE,"");//很重要,没有这一句,转换会失败。
intiWLen=mbstowcs(NULL,sToMatch.c_str(),sToMatch.length());//计算转换后宽字符串的长度。(不包含字符串结束符)
wchar_t*lpwsz=newwchar_t[iWLen+1];
inti=mbstowcs(lpwsz,sToMatch.c_str(),sToMatch.length());//转换。(转换后的字符串有结束符)
wstringwsToMatch(lpwsz);
delete[]lpwsz;
#endif
returnwsToMatch;
}
//把宽字符串转换成字符串,输出使用
stringwstring2string(wstringsToMatch)
{
#ifdef_A_WIN
stringsResult;
intiLen=WideCharToMultiByte(CP_ACP,NULL,sToMatch.c_str(),-1,NULL,0,NULL,FALSE);//计算转换后字符串的长度。(包含字符串结束符)
char*lpsz=newchar[iLen];
WideCharToMultiByte(CP_OEMCP,NULL,sToMatch.c_str(),-1,lpsz,iLen,NULL,FALSE);//正式转换。
sResult.assign(lpsz,iLen-1);//对string对象进行赋值。
delete[]lpsz;
#elif_A_LINUX
intiLen=wcstombs(NULL,sToMatch.c_str(),0);//计算转换后字符串的长度。(不包含字符串结束符)
char*lpsz=newchar[iLen+1];
inti=wcstombs(lpsz,sToMatch.c_str(),iLen);//转换。(没有结束符)
lpsz[iLen]='/0';
stringsResult(lpsz);
delete[]lpsz;
#endif
returnsResult;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!