随笔 - 171  文章 - 257  trackbacks - 0
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(33)

随笔分类(225)

随笔档案(171)

相册

技术

友情链接

最新随笔

搜索

  •  

积分与排名

  • 积分 - 441602
  • 排名 - 48

最新随笔

最新评论

阅读排行榜

评论排行榜

最近一段时间老弄Utf8编码,工作时写了几个函数,给大家指正一下

//////////////////////////////////////////////
//---------取得utf8字符的长度---------------//
//Str:String 源字符串
//Result:Integer utf8字符串长度
class function TPduPush.getUTF8Len(Str: string): Integer;
var
i: integer;
tmpChar: Pchar;
begin
tmpChar := pchar(str);
i := 0;
result := 0;
while i < length(tmpChar) do begin
if ord(tmpChar[i]) < $80 then begin
i := i + 1;
result := result + 1;
end else begin
i := i + 2;
result := result + 3;
end;
end;
end;

////////////////////////////////////////////////
//----------取得字符串中的字符个数------------//
//str:String 源字符串
//Result:Integer 字符个数,兼容中文双字节
class function TPduPush.getAnsiLen(Str: string): integer;
var
i: integer;
tmpChar: Pchar;
begin
tmpChar := pchar(str);
i := 0;
result := 0;
while i < length(tmpChar) do begin
if ord(tmpChar[i]) < $80 then
i := i + 1
else
i := i + 2;
result := result + 1;
end;
end;


/////////////////////////////////////////////////
//---------截取指定长度的utf8字符串------------//
//str:string 源字符串
//count:Integer 指定长度 一个汉字占三个字节,长度只能小,不能大
//Result:string 截取后的utf8字符串
class function TPduPush.getUTF8String(Str: string; count: Integer): string;
var
i, j: integer;
tmpChar: Pchar;
begin
tmpChar := pchar(str);
i := 0;
j := 0;
result := '';

while i < length(tmpChar) do begin
if j >= count then break; //英文转码后不能超过指定的位数
if ord(tmpChar[i]) < $80 then begin
result := result + string(tmpChar[i]);
i := i + 1;
j := j + 1;
end else begin
if j + 2 >= count then break; //汉字转码后不能超过指定的位数
result := result + string(tmpChar[i]) + string(tmpChar[i + 1]);
i := i + 2;
j := j + 3;
end;
end;
end;
posted on 2006-01-19 15:06 Khan 阅读(2153) 评论(1)  编辑 收藏 引用 所属分类: Delphi

FeedBack:
# re: 关于Utf8编码的几个函数 2012-06-06 20:34 肖伟立
请教一下QQ:36026877可以加QQ吗?  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理