在一條字符串中有多個空格
怎样取第三个到第四个空格之间的字符串
var
 i,k,m,n:integer;
 str:string;
begin
str:=trim(listbox1.Items[0]);
for i:=1 to Length(str) do
begin
  if str[i]=' ' then
  begin
    k:=K+1;
    if K=6 then
    begin
       m:=i;
    end;
    if K=8 then
    begin
       n:=i;
    end;
  end;
end;
showmessage(copy(listbox1.Items[0],m,n-m));
为什么这样得到的是整个字符串
在最后加上以下代码这OK了
showmessage(inttostr(n));

解决方案 »

  1.   

    给你一个函数
    function GetBlockStr(s:String;n:integer;BlockChar:char):String;
    var loc:integer;
    begin
      Loc:=pos(BlockChar,s);
      if Loc=0 then
        if n=1 then Result:=s else Result:=''
      else
        if n=1 then
          Result:=Copy(s,1,loc-1)
        else
          Result:=GetBlockStr(copy(s,loc+1,length(s)-loc),n-1,BlockChar);
    end;然后
    getblockstr( 你的字符串,4,' ') 就是你要的东西.  //  ' '是一个空格
      

  2.   

    将你的代码改了一下
    var
     i,k,m,n:integer;
     str:string;
    begin
    k:=0;
    str:=trim('123 4 5 6 7 89 999');
    for i:=1 to Length(str) do
    begin
      if str[i]=' ' then
      begin
        k:=K+1;
        if K=3 then m:=i;
        if K=4 then n:=i;
      end;
    end;
    showmessage(copy(str,m,n-m));
      

  3.   

    procedure TForm1.Button1Click(Sender: TObject);
    var
     i,k,m,n:integer;
     str:string;
    begin
    str:=trim(listbox1.Items[0]);
     k:=0 ; //加上这个
    for i:=1 to Length(str) do
    begin  if str[i]=' ' then
      begin
        k:=K+1;
        if K=3 then
        begin
           m:=i;
        end;
        if K=4 then
        begin
           n:=i;
        end;
      end;
      end;
       showmessage(copy(listbox1.Items[0],m,n-m));
    end;
      

  4.   

    var
     i,k,m,n:integer;
     str:string;
    begin
    str:=trim(listbox1.Items[0]);
    for i:=1 to Length(str) do
    begin
      if str[i]=' ' then
      begin
        k:=K+1;
        if K=3 then
        begin
           m:=i;
        end;
        if K=4 then
        begin
           n:=i;
        end;
      end;
    end;
    showmessage(copy(str,m,n-m+1));
      

  5.   

    用string类型的话汉字算两位,用ansistring汉字算1位