C++寬字符與普通字符的轉(zhuǎn)換實例詳解

C++寬字符與普通字符的轉(zhuǎn)換實例詳解

創(chuàng)新互聯(lián)是網(wǎng)站建設(shè)專家,致力于互聯(lián)網(wǎng)品牌建設(shè)與網(wǎng)絡(luò)營銷,專業(yè)領(lǐng)域包括成都網(wǎng)站設(shè)計、做網(wǎng)站、電商網(wǎng)站制作開發(fā)、微信平臺小程序開發(fā)、微信營銷、系統(tǒng)平臺開發(fā),與其他網(wǎng)站設(shè)計及系統(tǒng)開發(fā)公司不同,我們的整合解決方案結(jié)合了恒基網(wǎng)絡(luò)品牌建設(shè)經(jīng)驗和互聯(lián)網(wǎng)整合營銷的理念,并將策略和執(zhí)行緊密結(jié)合,且不斷評估并優(yōu)化我們的方案,為客戶提供全方位的互聯(lián)網(wǎng)品牌整合方案!

把字符串轉(zhuǎn)換成寬字符串,

實例代碼:

wstring string2Wstring(string sToMatch) 
{   
#ifdef _A_WIN 
  int iWLen = MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), 0, 0 ); // 計算轉(zhuǎn)換后寬字符串的長度。(不包含字符串結(jié)束符) 
  wchar_t *lpwsz = new wchar_t [iWLen + 1]; 
  MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), lpwsz, iWLen ); // 正式轉(zhuǎn)換。 
  lpwsz[iWLen] = L'/0';  
  wstring wsToMatch(lpwsz); 
  delete []lpwsz; 
#elif _A_LINUX 
  setlocale( LC_CTYPE, "" ); // 很重要,沒有這一句,轉(zhuǎn)換會失敗。 
  int iWLen = mbstowcs( NULL, sToMatch.c_str(), sToMatch.length() ); // 計算轉(zhuǎn)換后寬字符串的長度。(不包含字符串結(jié)束符) 
  wchar_t *lpwsz = new wchar_t[iWLen + 1]; 
  int i = mbstowcs( lpwsz, sToMatch.c_str(), sToMatch.length() ); // 轉(zhuǎn)換。(轉(zhuǎn)換后的字符串有結(jié)束符) 
  wstring wsToMatch(lpwsz); 
  delete []lpwsz; 
#endif 
  return wsToMatch; 
} 
//把寬字符串轉(zhuǎn)換成字符串,輸出使用 
string wstring2string(wstring sToMatch) 
{   
#ifdef _A_WIN 
  string sResult; 
  int iLen = WideCharToMultiByte( CP_ACP, NULL, sToMatch.c_str(), -1, NULL, 0, NULL, FALSE ); // 計算轉(zhuǎn)換后字符串的長度。(包含字符串結(jié)束符) 
  char *lpsz = new char[iLen]; 
  WideCharToMultiByte( CP_OEMCP, NULL, sToMatch.c_str(), -1, lpsz, iLen, NULL, FALSE); // 正式轉(zhuǎn)換。 
  sResult.assign( lpsz, iLen - 1 ); // 對string對象進(jìn)行賦值。 
  delete []lpsz; 
#elif _A_LINUX 
  int iLen = wcstombs( NULL, sToMatch.c_str(), 0 ); // 計算轉(zhuǎn)換后字符串的長度。(不包含字符串結(jié)束符) 
  char *lpsz = new char[iLen + 1]; 
  int i = wcstombs( lpsz, sToMatch.c_str(), iLen ); // 轉(zhuǎn)換。(沒有結(jié)束符) 
  lpsz[iLen] = '/0'; 
  string sResult(lpsz); 
  delete []lpsz; 
#endif 
  return sResult; 
} 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

本文題目:C++寬字符與普通字符的轉(zhuǎn)換實例詳解
標(biāo)題鏈接:http://bm7419.com/article44/igsjee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動網(wǎng)站建設(shè)、手機網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站、App開發(fā)、App設(shè)計、定制網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)