delphi 将字符串转换成 UTF8 编码的函数


本文整理自网络,侵删。

 这种转换一般用于网页地址; 我不知道 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;

相关阅读 >>

Delphi中查找进程及强行结束进程的方法

Delphi函数定时

Delphi 如何在数据表中存取图片

Delphi xe android将域名转化为ip

Delphi 释放bitmap

Delphi web service 多表提交的事务管理

Delphi 如何在tmemo,tedit或trichedit中获得插入符的位置

Delphi通过idsmtp发送邮件的简单代码

Delphi webbrowser1 execwb 复制 新建 打开

Delphi fmx播放m4a声音文件

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...