delphi按字节长度分割字符串函数(转)

此字符串分割函数用delphi编写,可以适应字符串中存在双字节字符和单字节字符。

function TricheditEfm.SplitString(source:string;Sleng:Integer):TStringlist;stdcall;  

                                                       //字符串分割函数 ,按字符串长度分割
var copycount,i:Integer;                               //每个汉字占用两个字节长度
    copystr:string;
    stringlist:Tstringlist;
begin
  Stringlist:=Tstringlist.Create;
  while length(source)>Sleng do
  begin
    copystr:=copy(source,1,Sleng);                    //以Sleng为长度截取字符串
    if (ord(bytetype(copystr[Sleng],1))=1) then       //如果最后一个字节是汉字
    begin
      copycount:=0;
      for i:=0 to Sleng-1 do
        if not (ord(bytetype(copystr[i],1))=1) then INC(copycount);
      if copycount mod 2 <>0 then             //有奇数个单字节字符,则说明是汉字的前半串
      begin
        stringlist.Add(Copy(Source,1,Sleng+1));
        source:=copy(source,Sleng+2,length(source)-Sleng-1);
      end
      else                                         //有偶数个单字节字符,则说明是汉字的后半串
      begin
        stringlist.Add(Copy(Source,1,Sleng));
        source:=copy(source,Sleng+1,length(source)-Sleng);
      end;
    end
    else                                          //如果最后一个字节是单字节字符
    begin
      stringlist.Add(Copy(Source,1,Sleng));
      source:=copy(source,Sleng+1,length(source)-Sleng);
    end;
  end;
  result:=Stringlist;
  Stringlist.Add(source);
end;
原文地址:https://www.cnblogs.com/blogpro/p/11339696.html