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

//////////////////////////////////////////////
//---------取得utf8字符的长度---------------//
//Str:String 源字符串
//Result:Integer utf8字符串长度
class function TPduPush.getUTF8Len(Strstring): Integer;
var
     i: integer;
     tmpChar: Pchar;
begin
     tmpChar := pchar(str);
     i := 0;
     result := 0;
     while i < length(tmpChar) do begin
          if ord(tmpChar) < $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(Strstring): integer;
var
     i: integer;
     tmpChar: Pchar;
begin
     tmpChar := pchar(str);
     i := 0;
     result := 0;
     while i < length(tmpChar) do begin
          if ord(tmpChar) < $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(Strstring; 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) < $80 then begin
               result := result + string(tmpChar);
               i := i + 1;
               j := j + 1;
          end else begin
               if j + 2 >= count then break;  //汉字转码后不能超过指定的位数
               result := result + string(tmpChar) + string(tmpChar[i + 1]);
               i := i + 2;
               j := j + 3;
          end;
     end;
end;