string与wstring转换

来源:互联网 发布:淘宝瓜子是什么类目 编辑:程序博客网 时间:2024/05/16 08:54

转自:http://www.cnblogs.com/02xiaoma/archive/2012/07/18/2597576.html


  • 方法一:MultiByteToWideChar、WideCharToMultiByte
复制代码
 1 BOOL StringToWString(const std::string &str,std::wstring &wstr) 2  {     3      int nLen = (int)str.length();     4      wstr.resize(nLen,L' '); 5   6      int nResult = MultiByteToWideChar(CP_ACP,0,(LPCSTR)str.c_str(),nLen,(LPWSTR)wstr.c_str(),nLen); 7   8      if (nResult == 0) 9      {10          return FALSE;11      }12  13      return TRUE;14  }15  //wstring高字节不为0,返回FALSE16  BOOL WStringToString(const std::wstring &wstr,std::string &str)17  {    18      int nLen = (int)wstr.length();    19      str.resize(nLen,' ');20  21      int nResult = WideCharToMultiByte(CP_ACP,0,(LPCWSTR)wstr.c_str(),nLen,(LPSTR)str.c_str(),nLen,NULL,NULL);22  23      if (nResult == 0)24      {25          return FALSE;26      }27  28      return TRUE;29  }
复制代码
  • 方法二:std::copy
复制代码
 1 std::wstring StringToWString(const std::string &str) 2  { 3      std::wstring wstr(str.length(),L' '); 4      std::copy(str.begin(), str.end(), wstr.begin()); 5      return wstr;  6  } 7   8  //只拷贝低字节至string中 9  std::string WStringToString(const std::wstring &wstr)10  {11      std::string str(wstr.length(), ' ');12      std::copy(wstr.begin(), wstr.end(), str.begin());13      return str; 14  }
复制代码

0 0
原创粉丝点击