字符串转换成宽字符串,把宽字符串转换成字符串

57 篇文章 0 订阅
//把字符串转换成宽字符串
02
wstring string2Wstring(string sToMatch)
03
{  
04
#ifdef _A_WIN
05
    intiWLen = MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), 0, 0 );// 计算转换后宽字符串的长度。(不包含字符串结束符)
06
    wchar_t*lpwsz = newwchar_t [iWLen + 1];
07
    MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), lpwsz, iWLen ); // 正式转换。
08
    lpwsz[iWLen] = L'/0';
09
    wstring wsToMatch(lpwsz);
10
    delete[]lpwsz;
11
#elif _A_LINUX
12
    setlocale( LC_CTYPE, ""); // 很重要,没有这一句,转换会失败。
13
    intiWLen = mbstowcs( NULL, sToMatch.c_str(), sToMatch.length() ); // 计算转换后宽字符串的长度。(不包含字符串结束符)
14
    wchar_t*lpwsz = newwchar_t[iWLen + 1];
15
    inti = mbstowcs( lpwsz, sToMatch.c_str(), sToMatch.length() ); // 转换。(转换后的字符串有结束符)
16
    wstring wsToMatch(lpwsz);
17
    delete[]lpwsz;
18
#endif
19
    returnwsToMatch;
20
}
21
//把宽字符串转换成字符串,输出使用
22
string wstring2string(wstring sToMatch)
23
{  
24
#ifdef _A_WIN
25
    string sResult;
26
    intiLen = WideCharToMultiByte( CP_ACP, NULL, sToMatch.c_str(), -1, NULL, 0, NULL, FALSE );// 计算转换后字符串的长度。(包含字符串结束符)
27
    char*lpsz = newchar[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
    intiLen = wcstombs( NULL, sToMatch.c_str(), 0 ); // 计算转换后字符串的长度。(不包含字符串结束符)
33
    char*lpsz = newchar[iLen + 1];
34
    inti = wcstombs( lpsz, sToMatch.c_str(), iLen ); // 转换。(没有结束符)
35
    lpsz[iLen] = '/0';
36
    string sResult(lpsz);
37
    delete[]lpsz;
38
#endif
39
    returnsResult;
40
}


转自:http://bbs.unix8.net/thread-233-1-1.html
   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值