string-->wstring-->string

	std::string src("三毛三毛三毛三毛三三三三流浪记");

 	size_t size = mbstowcs(NULL,src.c_str(),0);
 	std::wstring dst;
 	dst.resize(size);
 	setlocale(LC_CTYPE,"chs");//setlocale(LC_CTYPE,"UTF-8") on mac
 	mbstowcs(&dst[0],src.c_str(),size); 
	wstring::size_type pos = dst.find_first_of(L'\0'); // L'\0' or wchar_t()
 	dst = dst.substr(0,pos);
 	stable_sort(dst.begin(),dst.end());
 	wstring::iterator it = unique(dst.begin(),dst.end());
 	dst.erase(it,dst.end());
 	size_t newSize = wcstombs(NULL,dst.c_str(),0);
 	string newStr;
 	newStr.resize(newSize);
 	wcstombs(&newStr[0],dst.c_str(),newSize);
 	setlocale(LC_ALL,"C");

 

wcstombs:

  http://msdn.microsoft.com/zh-cn/subscriptions/downloads/5d7tc9zw(v=vs.71).aspx

     mbstowcs(NULL,src.c_str(),0) 返回的wstring需要的长度,比实际需要的多

    导致wstring.resize的时候,多了许多'\0' ,经过排序去重后,'\0'在最前面

         wcstombs 看到'\0' 立马结束,返回string的长度需要0,导致错误。

  If wcstombs encounters the wide-character null character (L'\0') either before or when count occurs, it converts it to an 8-bit 0 and stops. Thus, the multibyte character string at mbstr is null-terminated only if wcstombs encounters a wide-character null character during conversion. If the sequences pointed to by wcstrand mbstr overlap, the behavior of wcstombs is undefined.

 

 

 

转载于:https://www.cnblogs.com/ezhong/p/3559693.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值