这种转换一般用于网页地址; 我不知道 Delphi 是不是有现成的函数, 用到了就写了一个.
//函数: function ToUTF8Encode(str: string): string; var b: Byte; begin for b in BytesOf(UTF8Encode(str)) do Result := Format(‘%s%%%.2x‘, [Result, b]); end; //测试: var str: string; begin str := ‘大雄‘; str := ToUTF8Encode(str); ShowMessage(str); //%E4%B8%87%E4%B8%80 end;
为 "小月124" 写了个反向函数:
function ToUTF8Decode(const str: string): string; var List: TStrings; tmpStr: AnsiString; i: Integer; begin List := TStringList.Create; ExtractStrings([‘%‘], [‘%‘], PChar(str), List); SetLength(tmpStr, List.Count); for i := 0 to List.Count - 1 do Byte(tmpStr[i+1]) := StrToInt(‘$‘ + List[i]); List.Free; Result := UTF8Decode(tmpStr); end; { 调用测试 } procedure TForm1.FormCreate(Sender: TObject); var s1: AnsiString; s2: WideString; begin s1 := ‘%E4%B8%87%E4%B8%80‘; s2 := ToUTF8Decode(s1); ShowMessage(s2); { 大雄 } end;
时间: 2024-10-01 05:57:19