Delphi实现AnsiString与WideString的转换函数 转

Delphi实现AnsiString与WideString的转换函数

分类: Delphi 460人阅读 评论(0) 收藏 举报
[delphi] view plaincopy
  1. 在Delphi下,AnsiString 和 WideString 的存储与管理各有不同,这里提供互相转换的函数一对。  
  2. /// Wide String -> Ansi String  
  3. function WideStringToAnsiString(const strWide: WideString; CodePage: Word): AnsiString;  
  4. var  
  5.   Len: integer;  
  6. begin  
  7.   Result := '';  
  8.   if strWide = '' then Exit;  
  9.    
  10.   Len := WideCharToMultiByte(CodePage,  
  11.     WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,  
  12.     @strWide[1], -1nil0nilnil);  
  13.   SetLength(Result, Len - 1);  
  14.   
  15.   if Len > 1 then  
  16.     WideCharToMultiByte(CodePage,  
  17.       WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,  
  18.       @strWide[1], -1, @Result[1], Len - 1nilnil);  
  19. end;  
  20.   
  21. /// Ansi String -> Wide String  
  22. function AnsiStringToWideString(const strAnsi: AnsiString; CodePage: Word): WideString;  
  23. var  
  24.   Len: integer;  
  25. begin  
  26.   Result := '';  
  27.   if strAnsi = '' then Exit;  
  28.   
  29.   Len := MultiByteToWideChar(CodePage, MB_PRECOMPOSED, PChar(@strAnsi[1]), -1nil0);  
  30.   SetLength(Result, Len - 1);  
  31.    
  32.   if Len > 1 then  
  33.     MultiByteToWideChar(CodePage, MB_PRECOMPOSED, PChar(@strAnsi[1]), -1, PWideChar(@Result[1]), Len - 1);  
  34. end;  
  35.   
  36. 调用时需要传入 CodePage 参数,如果是简体中文环境,则 CodePage = 936(可以使用API函数GetACP获取系统默认CodePage)  
原文地址:https://www.cnblogs.com/zhangzhifeng/p/3301099.html