打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Lazarus中一个处理UTF8编码的类

功能:Lazarus中一个处理UTF8编码的类;

constructor TUTF8String.Create;

begin

Fvalue:='';

FCharsCount:=0;

FisErrorUTF8String:=false;

end;

function TUTF8String.GetUTF8Char(index:integer):string;

var

c:char;pc:pchar;b:byte;i,L,counter,cL,sp:integer;

begin

L:=length(FValue);

result:='';     sp:=0;

pc:=Pchar(Fvalue); counter:=0;

for i:=0 to L-1 do

begin

c:=PC^;   b:=byte(c);

if (b and $FC)=$FC then CL:=6

else if (b and $F8)=$F8 then CL:=5

else if (b and $F0)=$F0 then CL:=4

else if (b and $E0)=$E0 then CL:=3

else if (b and $C0)=$C0 then CL:=2

else if (b and $80)<>$80 then CL:=1

else CL:=0; //非UTF8字符头字节,错误

if CL<>0 then begin

inc(counter);

if counter-1=index then

begin

result:=copy(Fvalue,sp+1,CL);  //copy从1开始计算位置。

exit;

end;

PC:=PC+CL;

sp:=sp+CL;

end else begin PC:=PC+1; inc(sp); end;

if sp>=L then  break;

end;

end;

procedure TUTF8String.SetValue(s:string);

var

c:char;pc:pchar;b:byte;i,L,counter,cL,sp:integer;

begin

if Fvalue<>s then

begin

Fvalue:=s;

sp:=0;//指针对应字符坐标计数器

FisErrorUTF8String:=false;

L:=length(FValue);

pc:=Pchar(Fvalue); counter:=0;

for i:=0 to L-1 do

begin

c:=PC^;   b:=byte(c);

if    (b and $FC)=$FC then CL:=6  //CL为根据开头字节判断出的UTF8字符长度

else if (b and $F8)=$F8 then CL:=5

else if (b and $F0)=$F0 then CL:=4

else if (b and $E0)=$E0 then CL:=3

else if (b and $C0)=$C0 then CL:=2

else if (b and $80)<>$80 then CL:=1

else begin CL:=0;FisErrorUTF8String:=true end; //非UTF8字符头字节,错误

if CL<>0 then

begin

inc(counter);

PC:=PC+CL;

sp:=sp+CL;

end else begin PC:=PC+1; inc(sp); end;

if sp>L then //指针超长,错误!

begin

FisErrorUTF8String:=true;

break;

end else if sp=L then break; //指针刚好指向结尾,正常结束

end;

self.Fcharscount:=counter;

end;

end;

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Delphi 关键字详解[整理于 "橙子" 的帖子]
文件批量改名工具官网–新起飞部落 ? lazarus UTF8 unicode
What is love
java: utf-8转unicode
jspsmart字符编码的问题
xcode nslog输出不全问题解决
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服