分享

宽字符和窄字符的转换接口

 拜书者 2015-02-28

作者:朱金灿

来源:http://blog.csdn.net/clever101

 

     宽字符和窄字符的转换需求很经常会遇到,今天从网上找了两个函数,修改了一下,奉献给大家。

  1. #include <string>  
  2. #include <assert.h>  
  3.   
  4. std::wstring toWideString( const char* pStr,int len)  
  5. {  
  6.     assert(pStr) ;   
  7.     assert(len >= 0 || len == -1, _T("Invalid string length: ") << len ) ;  
  8.   
  9.     // figure out how many wide characters we are going to get   
  10.     int nChars = MultiByteToWideChar( CP_ACP , 0 , pStr , len , NULL , 0 ) ;   
  11.     if ( len == -1 )  
  12.         -- nChars ;   
  13.     if ( nChars == 0 )  
  14.         return L"" ;  
  15.   
  16.     // convert the narrow string to a wide string   
  17.     // nb: slightly naughty to write directly into the string like this  
  18.     std::wstring buf;  
  19.     buf.resize(nChars);   
  20.     ::MultiByteToWideChar(CP_ACP,0,pStr,len,const_cast<wchar_t*>(buf.c_str()),nChars);   
  21.   
  22.     return buf ;  
  23. }  
  24.   
  25. std::wstring toWideString(const std::string& strA)  
  26. {  
  27.     const char* pStr = strA.c_str();  
  28.     int len = strA.length();  
  29.     return toWideString(pStr,len);  
  30. }  
  31.   
  32. std::string toNarrowString( const wchar_t* pStr,int len)  
  33. {      
  34.     // figure out how many narrow characters we are going to get   
  35.     assert(pStr) ;   
  36.     assert(len >= 0 || len == -1 , _T("Invalid string length: ") << len ) ;   
  37.   
  38.     int nChars = WideCharToMultiByte( CP_ACP , 0 ,   
  39.         pStr , len , NULL , 0 , NULL , NULL ) ;   
  40.     if ( len == -1 )  
  41.         -- nChars ;   
  42.     if ( nChars == 0 )  
  43.         return "" ;  
  44.   
  45.     // convert the wide string to a narrow string  
  46.     // nb: slightly naughty to write directly into the string like this  
  47.     std::string buf ;  
  48.     buf.resize(nChars);  
  49.     WideCharToMultiByte(CP_ACP,0,pStr,len,const_cast<char*>(buf.c_str()),nChars,NULL,NULL);   
  50.   
  51.     return buf ;   
  52. }  
  53.   
  54. std::string toNarrowString(const std::wstring& strW)  
  55. {  
  56.     const wchar_t* pStr = strW.c_str();  
  57.     int len = strW.length();  
  58.     return toNarrowString(pStr,len);  
  59. }  

      有问题或者更好意见的话请联系我。

 

参考文献:

 

1. 如何升级基于STL的应用来支持Unicode


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多