中英文和字符混合的情况下,如何定长截断字符串,比如:定长截断60位?
因为牵涉有汉字,最后一位有可能截为乱码(我实际遇到过这种情况,搞的数据
库不能查询),如何避免这种情况,当然,如果最后一个字符是汉字,截断59位
也可,请大侠指教。

解决方案 »

  1.   

    读取最后一个字的UNICODE代码,判断其最后两位是否为0的,
      

  2.   

    uses StrUtils ;  MidBStr(Edit1.Text, 1, 60)
      

  3.   

    huayuxing兄,如何度曲UNICODE代码?并且,问题是你如何判断最后一个字,由于中英文符号混杂,无法知道哪一个是最后一个字,有可能是中文,有可能是英文或字符。
      

  4.   

    meiqingsong兄,你这个函数我试过了,有问题,比如这个
    字符“Edit10000中国”,我用MidBStr(Edit1.Text, 1, 10)截
    端后,借端10个字符,变成了“Edit10000[”,最后一个是乱
    码,转到数据库中是个空格,其实不是个空格,是个乱码,只
    是无法显示而已。
      

  5.   

    function MyCopy(source:string;aSize:Integer):string;
    var
      r1,r2:string;
      w1,w2:widestring;
    begin
      r1:=Copy(source,1,aSize+1);
      r2:=Copy(source,1,aSize);  w1:=r1;
      w2:=r2;
      if Length(w1)=Length(w2) then
      begin
        result:=copy(source,1,aSize-1);
      end
      else
        Result:=r2;
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
      s1,s2:string;
    begin
      s1:='Edit01000中国';
      s2:=MyCopy(s1,10);
      ShowMessage(s2);end;
      

  6.   

    s := Copy(Edit1.Text, 1, 59) + Copy(WideString(Edit1.Text), 10, 60);
      

  7.   

    这个我测试了,没有问题的,能很好处理汉字尾巴
    function TForm1.get60(str: String; len: Integer): string;
    var
      i, n, ntotal, nstep: integer;
      wstr:WideString;
    begin
      wstr:=WideString(str);
      ntotal := 0;
      result := '';
      for i := 1 to length(wstr) do
      begin
        if WORD(wstr[i]) > 256 then nstep := 2 else nstep := 1;
        if ntotal + nstep <= len then
        begin
          result := result + wstr[i];
          ntotal := ntotal + nstep;
        end
        else
          exit;
      end;
    end;procedure TForm1.BitBtn1Click(Sender: TObject);
    var
      st, s: string;
    begin
      st := 'ddd我们cvb的祖国';
      s := get60(st, 13);
      ShowMessage(s);
    end;
      

  8.   

    s := Copy(Edit1.Text, 1, 59) + Copy(WideString(Edit1.Text), 60, 1);
      

  9.   

    汉字的第一位>0xa0,按照这个比较就行了
    要不就用widestring