如题:
用Copy函数提取子字符串时,怎样防止将中文截断,出现半个字符的情况发生?字符串是中英文混排的。

解决方案 »

  1.   

    使用widestring
    var ws : widestring;s1,s2,s3:string;l:integer;
    begin
    ws := '你的字符串';
    l := length(ws) div 3;
    s1 := copy(ws,1,l);
    s2 := copy (ws,l+1,l);
    s3 := copy (2*l +1,255);
    ////还有
    //***************************//
    //**涵数功能:获取子串********//
    //**参数1:字符串*************//
    //**参数2:子串起始位置*******//
    //**参数3:子串的长度*********//
    //***************************//
    function GetSubString(strInfor: string; startPos,endPos: integer): string;
    var
       charA:char;  //临时字符
       intI,intCount:integer;
    begin
       //检查参数
       if (strinfor='') or (startpos<1) or (startpos>length(strinfor))
          or (endpos<1) then
       begin
          result:='';
          exit;
       end; //if   //第一个字符开始取的直接取即可
       if startpos=1 then
       begin
          result:=copy(strinfor,startpos,endpos);
          exit;
       end;   //统计非中文字数
       intcount:=0;
       for inti:=1 to startpos-1 do
       begin
          chara:=strinfor[inti];
          if ord(chara)<=127 then
             inc(intcount);
       end;   //偶数个非中文字数则需从奇数开始取
       //奇数个非中文字数则需从偶数开始取
       if ( (intcount mod 2=0) and (startpos mod 2=0) ) or
          ( (intcount mod 2=1) and (startpos mod 2=1) ) then
       begin
          result:=copy(strinfor,startpos-1,endpos+1);
          exit;
       end;   //其它情况则正常读取
       result:=copy(strinfor,startpos,endpos);end;
      

  2.   

    方法一:
    function ByteType(const S: string; Index: Integer): TMbcsByteType;
    type TMbcsByteType = (mbSingleByte, mbLeadByte, mbTrailByte);
      其中Index的参数为1, s为目标字符串. mbSingleByte表示是单字节
      mbLeadByte表示是双字节第一位,mbTrailByte 表示是双字节第二位方法二: 输入参数S 可以包含有 中文, 函数的返回值是S中所有的中文
      function GetChinaese(S: string): string;
    var
      i,j,n:integer;
    begin
      i:=0 ;
      j:=0 ;
      n:=length(S);
      while i<n do
      begin
        if Byte(S[i]) in [$a1..$fe] then //是汉字首字符
        begin
          result:=result+s[i]+s[i+1];
          inc(j);
          inc(i);
        end;
        Inc(i);
      end;
    end;
      

  3.   

    procedure TForm1.Button3Click(Sender: TObject);
    var
      s,str:string;
      i,j:integer;
    begin
      s:='中华人民共和国';
      i:=strtoint(form1.Edit1.Text);
      j:=ord(s[i]);
      if j>128 then
        str:=copy(s,1,i+1)
      else
        str:=copy(s,1,i);
      showmessage(str);
    end;