1. 程式人生 > >各種型別字元之間的轉換(單位元組char*和寬位元組wchar_t*,TCHAR和string的轉換)

各種型別字元之間的轉換(單位元組char*和寬位元組wchar_t*,TCHAR和string的轉換)

  1. //將單位元組char*轉化為寬位元組wchar_t*
  2. wchar_t* AnsiToUnicode( constchar* szStr )  
  3. {  
  4.     int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0 );  
  5.     if (nLen == 0)  
  6.     {  
  7.         return NULL;  
  8.     }  
  9.     wchar_t* pResult = newwchar_t[nLen];  
  10.     MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );  
  11.     return pResult;  
  12. }  
  13. //將寬位元組wchar_t*轉化為單位元組char*
  14. inlinechar* UnicodeToAnsi( constwchar_t* szStr )  
  15. {  
  16.     int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );  
  17.     if (nLen == 0)  
  18.     {  
  19.         return NULL;  
  20.     }  
  21.     char* pResult = newchar[nLen];  
  22.     WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );  
  23.     return pResult;  
  24. //在unicode環境下將TCHAR 轉換為std::string

  25. inline std::string TCHAR2STRING(TCHAR* str)
  26. {
  27. int nlen=WideCharToMultiByte(CP_ACP,0,str,-1,NULL,0,NULL,NULL);
  28. char* res=new char[nlen*sizeof(char)];
  29. WideCharToMultiByte(CP_ACP,0,str,-1,res,0,NULL,NULL);
  30. return string(res);
  31. }