unit1.pas

来自「UTF8与string类型中的相互转换 delphi7源码」· PAS 代码 · 共 82 行

PAS
82
字号
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    SourceEdit: TEdit;
    ResultEdit: TEdit;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
function Utf8ToAnsi(x: string): ansistring;
  { Function that recieves UTF8 string and converts 
    to ansi string } 
var 
  i: integer; 
  b1, b2: byte; 
begin 
  Result := x;
  i := 1; 
  while i <= Length(Result) do begin 
    if (ord(Result[i]) and $80) <> 0 then begin 
      b1 := ord(Result[i]); 
      b2 := ord(Result[i + 1]); 
      if (b1 and $F0) <> $C0 then 
        Result[i] := #128 
      else begin 
        Result[i] := Chr((b1 shl 6) or (b2 and $3F)); 
        Delete(Result, i + 1, 1); 
      end; 
    end; 
    inc(i); 
  end; 
end; 


function AnsiToUtf8(x: ansistring): string;
  { Function that recieves ansi string and converts 
    to UTF8 string } 
var 
  i: integer; 
  b1, b2: byte; 
begin 
  Result := x; 
  for i := Length(Result) downto 1 do 
    if Result[i] >= #127 then begin 
      b1 := $C0 or (ord(Result[i]) shr 6); 
      b2 := $80 or (ord(Result[i]) and $3F); 
      Result[i] := chr(b1); 
      Insert(chr(b2), Result, i + 1); 
    end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
  self.ResultEdit.Text:= AnsiToUtf8(self.SourceEdit.Text);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  self.SourceEdit.Text:= Utf8ToAnsi(self.ResultEdit.Text);

end;

end.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?