最近一段時(shí)間老弄Utf8編碼,工作時(shí)寫了幾個(gè)函數(shù),給大家指正一下
//////////////////////////////////////////////
//---------取得utf8字符的長(zhǎng)度---------------//
//Str:String 源字符串
//Result:Integer utf8字符串長(zhǎng)度
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;
////////////////////////////////////////////////
//----------取得字符串中的字符個(gè)數(shù)------------//
//str:String 源字符串
//Result:Integer 字符個(gè)數(shù),兼容中文雙字節(jié)
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;
/////////////////////////////////////////////////
//---------截取指定長(zhǎng)度的utf8字符串------------//
//str:string 源字符串
//count:Integer 指定長(zhǎng)度 一個(gè)漢字占三個(gè)字節(jié),長(zhǎng)度只能小,不能大
//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; //英文轉(zhuǎn)碼后不能超過(guò)指定的位數(shù)
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; //漢字轉(zhuǎn)碼后不能超過(guò)指定的位數(shù)
result := result + string(tmpChar[i]) + string(tmpChar[i + 1]);
i := i + 2;
j := j + 3;
end;
end;
end;