例:s:='1,2,3,4,5'
现在我想截取到第三个逗号前字符串,像s1:='1,2,3';

解决方案 »

  1.   

    LeftStr(str,n):从左向右,截取n个字符 
     RightStr(str,n):从右向左 
     Copy(str,index,n):从任意位置,截取n个字符
      

  2.   

    //一个比较傻的方法
    var
      i,j:integer;
      //......
    begin
      s1:='';
      j:=0;
      for i:=1 to Length(s) do
      begin
        if IsDelimiter(',',s,i) then inc(j);
        if j<3 then
          s1:=s1+s[i]
        else break;
      end;
    end;
      

  3.   

    先要找到第三个逗号的位置,可以循环比较
    然后用LeftStr
      

  4.   

    直接用LeftStr肯定不行,并不知道字符串的实际长度。
    function GetSubStr(strData: string): string;
    var
      strTmp: string;
      iCount, iPostion: Integer;
      bOver: Boolean;
    begin
      Result := '';
      strTmp := strData;
      iCount := 0;
      bOver := False;
      while (iCount < 3) and (not bOver) do
      begin
        iPosition := Pos(',', strTmp);
        if iPosition = 0 then
          bOver := True
        else
          begin
            strTmp[iPosition] := '#';
            iCount := iCount + 1;
          end
      end;
      if iCount = 3 then
        Result := Copy(strData, 1, iPosition);
    end;
      

  5.   

    呵呵,有点错了。var中iPosition写错了,最后Result中应该是iPosition - 1.