C++寬字符與普通字符的轉換實例詳解
把字符串轉換成寬字符串,
實例代碼:
wstring string2Wstring(string sToMatch) {   #ifdef _A_WIN   int iWLen = MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), 0, 0 ); // 計算轉換后寬字符串的長度。(不包含字符串結束符)   wchar_t *lpwsz = new wchar_t [iWLen + 1];   MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), lpwsz, iWLen ); // 正式轉換。   lpwsz[iWLen] = L'/0';    wstring wsToMatch(lpwsz);   delete []lpwsz; #elif _A_LINUX   setlocale( LC_CTYPE, "" ); // 很重要,沒有這一句,轉換會失敗。   int iWLen = mbstowcs( NULL, sToMatch.c_str(), sToMatch.length() ); // 計算轉換后寬字符串的長度。(不包含字符串結束符)   wchar_t *lpwsz = new wchar_t[iWLen + 1];   int i = mbstowcs( lpwsz, sToMatch.c_str(), sToMatch.length() ); // 轉換。(轉換后的字符串有結束符)   wstring wsToMatch(lpwsz);   delete []lpwsz; #endif   return wsToMatch; } //把寬字符串轉換成字符串,輸出使用 string wstring2string(wstring sToMatch) {   #ifdef _A_WIN   string sResult;   int iLen = WideCharToMultiByte( CP_ACP, NULL, sToMatch.c_str(), -1, NULL, 0, NULL, FALSE ); // 計算轉換后字符串的長度。(包含字符串結束符)   char *lpsz = new char[iLen];   WideCharToMultiByte( CP_OEMCP, NULL, sToMatch.c_str(), -1, lpsz, iLen, NULL, FALSE); // 正式轉換。   sResult.assign( lpsz, iLen - 1 ); // 對string對象進行賦值。   delete []lpsz; #elif _A_LINUX   int iLen = wcstombs( NULL, sToMatch.c_str(), 0 ); // 計算轉換后字符串的長度。(不包含字符串結束符)   char *lpsz = new char[iLen + 1];   int i = wcstombs( lpsz, sToMatch.c_str(), iLen ); // 轉換。(沒有結束符)   lpsz[iLen] = '/0';   string sResult(lpsz);   delete []lpsz; #endif   return sResult; } 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選