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:ide
http://msdn.microsoft.com/zh-cn/subscriptions/downloads/5d7tc9zw(v=vs.71).aspxspa
mbstowcs(NULL,src.c_str(),0) 返回的wstring須要的長度,比實際須要的多blog
致使wstring.resize的時候,多了許多'\0' ,通過排序去重後,'\0'在最前面排序
wcstombs 看到'\0' 立馬結束,返回string的長度須要0,致使錯誤。ip
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.string