Delphi2010中Ansi字符串与Unicode字符互转方法
Delphi2010及以上版本后,默认的字符串类型由原来的单字节Ansi型改成了Unicode型,造成原来的一些原代码无法运行,现提供一个互转的函数供大家使用,在Delphi2010+WIN7上调试通过。
一、Ansi型转Unicode型
|
1 2 3 4 5 6 7 8 9 10 |
function AnsiToUnicode(Str: AnsiString): String; var Len: integer; begin Len := Length(Str) + 1; SetLength(Result, Len); Len := MultiByteToWideChar(CP_ACP, 0, PAnsiChar(Str), -1, PWideChar(Result), Len); SetLength(Result, Len - 1); // end is #0 end; |
二、Unicode型转Ansi型
|
1 2 3 4 5 6 7 8 9 10 |
function UnicodeToAnsi(Str: String): AnsiString; var Len: integer; begin Len := Length(Str) * 2 + 1; // one for #0 SetLength(Result, Len); Len := WideCharToMultiByte(CP_ACP, 0, PWideChar(Str), -1, PAnsiChar(Result), Len, nil, nil); SetLength(Result, Len - 1); end; |
三、调用举例:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
procedure TForm3.Button1Click(Sender: TObject); var ans: AnsiString; Str: String; I: integer; begin ans := UnicodeToAnsi(Edit1.Text); I := 1; while I <= Length(ans) do begin Memo1.Lines.Add(IntToHex(ord(ans[I]), 2) + IntToHex(ord(ans[I + 1]), 2)); I := I + 2; end; I := 1; Str := AnsiToUnicode(ans); while I <= Length(str) do begin Memo1.Lines.Add(IntToHex(ord(str[I]), 4)); I := I + 1; end; end; |