function UTF8Encode(const ASrc: string): string; const UnsafeChars = ['*', '#', '%', '<', '>', '+', ' ']; {do not localize} var i: Integer; begin Result := ''; {Do not Localize} for i := 1 to Length(ASrc) do begin if (ASrc[i] in UnsafeChars) or (ASrc[i] >= #$80) or (ASrc[i] < #32) then begin Result := Result + '%' + IntToHex(Ord(ASrc[i]), 2); {do not localize} end else begin Result := Result + ASrc[i]; end; end; end;procedure TForm1.FormCreate(Sender: TObject); begin Label1.Caption:= UTF8Encode('猪头'); end;
delphi 6里的fastNet面版有个nmURL的控件.可以实现这种转换,并且可以双向转换. var st:string; begin nmurl1.InputString:='猴子'; st:nmurl1.Decode: end;
你处理你的字符串,每次1个字节,发现大于127就输出%ce这样的,不大于127就原样输出
const
UnsafeChars = ['*', '#', '%', '<', '>', '+', ' ']; {do not localize}
var
i: Integer;
begin
Result := ''; {Do not Localize}
for i := 1 to Length(ASrc) do begin
if (ASrc[i] in UnsafeChars) or (ASrc[i] >= #$80) or (ASrc[i] < #32) then begin
Result := Result + '%' + IntToHex(Ord(ASrc[i]), 2); {do not localize}
end else begin
Result := Result + ASrc[i];
end;
end;
end;procedure TForm1.FormCreate(Sender: TObject);
begin
Label1.Caption:= UTF8Encode('猪头');
end;
var
st:string;
begin
nmurl1.InputString:='猴子';
st:nmurl1.Decode:
end;