string与wstring转换

转自: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,返回FALSE
16  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  }
复制代码

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值