Khan's Notebook GCC/GNU/Linux Delphi/Window Java/Anywhere

路漫漫,长修远,我们不能没有钱
随笔 - 172, 文章 - 0, 评论 - 257, 引用 - 0
数据加载中……

关于Utf8编码的几个函数

最近一段时间老弄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 阅读(2160) 评论(1)  编辑 收藏 引用 所属分类: Delphi

评论

# re: 关于Utf8编码的几个函数  回复  更多评论   

请教一下QQ:36026877可以加QQ吗?
2012-06-06 20:34 | 肖伟立

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