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

Delphi实现AnsiString与WideString的转换函数

分类: Delphi2013-01-26 16:23 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. Len := WideCharToMultiByte(CodePage,
  10. WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,
  11. @strWide[1], -1, nil, 0, nil, nil);
  12. SetLength(Result, Len - 1);
  13. if Len > 1 then
  14. WideCharToMultiByte(CodePage,
  15. WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,
  16. @strWide[1], -1, @Result[1], Len - 1, nil, nil);
  17. end;
  18. /// Ansi String -> Wide String
  19. function AnsiStringToWideString(const strAnsi: AnsiString; CodePage: Word): WideString;
  20. var
  21. Len: integer;
  22. begin
  23. Result := '';
  24. if strAnsi = '' then Exit;
  25. Len := MultiByteToWideChar(CodePage, MB_PRECOMPOSED, PChar(@strAnsi[1]), -1, nil, 0);
  26. SetLength(Result, Len - 1);
  27. if Len > 1 then
  28. MultiByteToWideChar(CodePage, MB_PRECOMPOSED, PChar(@strAnsi[1]), -1, PWideChar(@Result[1]), Len - 1);
  29. end;
  30. 调用时需要传入 CodePage 参数,如果是简体中文环境,则 CodePage = 936(可以使用API函数GetACP获取系统默认CodePage)