C++宽字符与普通字符的相互转换方法

来源:互联网 发布:江苏盐城大数据产业园 编辑:程序博客网 时间:2024/04/28 13:36
  1. //把字符串转换成宽字符串  
  2. wstring string2Wstring(string sToMatch)  
  3. {     
  4. #ifdef _A_WIN  
  5.     int iWLen = MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), 0, 0 ); // 计算转换后宽字符串的长度。(不包含字符串结束符)  
  6.     wchar_t *lpwsz = new wchar_t [iWLen + 1];  
  7.     MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), lpwsz, iWLen ); // 正式转换。  
  8.     lpwsz[iWLen] = L'/0';   
  9.     wstring wsToMatch(lpwsz);  
  10.     delete []lpwsz;  
  11. #elif _A_LINUX  
  12.     setlocale( LC_CTYPE, "" ); // 很重要,没有这一句,转换会失败。  
  13.     int iWLen = mbstowcs( NULL, sToMatch.c_str(), sToMatch.length() ); // 计算转换后宽字符串的长度。(不包含字符串结束符)  
  14.     wchar_t *lpwsz = new wchar_t[iWLen + 1];  
  15.     int i = mbstowcs( lpwsz, sToMatch.c_str(), sToMatch.length() ); // 转换。(转换后的字符串有结束符)  
  16.     wstring wsToMatch(lpwsz);  
  17.     delete []lpwsz;  
  18. #endif  
  19.     return wsToMatch;  
  20. }  
  21. //把宽字符串转换成字符串,输出使用  
  22. string wstring2string(wstring sToMatch)  
  23. {     
  24. #ifdef _A_WIN  
  25.     string sResult;  
  26.     int iLen = WideCharToMultiByte( CP_ACP, NULL, sToMatch.c_str(), -1, NULL, 0, NULL, FALSE ); // 计算转换后字符串的长度。(包含字符串结束符)  
  27.     char *lpsz = new char[iLen];  
  28.     WideCharToMultiByte( CP_OEMCP, NULL, sToMatch.c_str(), -1, lpsz, iLen, NULL, FALSE); // 正式转换。  
  29.     sResult.assign( lpsz, iLen - 1 ); // 对string对象进行赋值。  
  30.     delete []lpsz;  
  31. #elif _A_LINUX  
  32.     int iLen = wcstombs( NULL, sToMatch.c_str(), 0 ); // 计算转换后字符串的长度。(不包含字符串结束符)  
  33.     char *lpsz = new char[iLen + 1];  
  34.     int i = wcstombs( lpsz, sToMatch.c_str(), iLen ); // 转换。(没有结束符)  
  35.     lpsz[iLen] = '/0';  
  36.     string sResult(lpsz);  
  37.     delete []lpsz;  
  38. #endif  
  39.     return sResult;  
  40. }  
0 0
原创粉丝点击