有类似如下一字符串:“2:牛 4:鸡 1:猪 3:虎 8:猴 3:马”如何实现按生肖前面的数值从大小到的顺序排列,即得到如下字串:“8:猴 4:鸡 3:虎 3:马 2:牛 1:猪”

解决方案 »

  1.   

    放到TStringList里, 调用Sort方法
      

  2.   

    sort可以针对这种字符吗,我也有这样想过
      

  3.   

    用tstringlist的CustomSort就可以了,如:
    function mycomp(List: TStringList; Index1, Index2: Integer): Integer;
    var
      p,n1,n2:integer;
      s:string;
    begin
      p:=pos(':',list.Strings[index1]);
      n1:=StrToInt(copy(list.Strings[index1],1,p-1));
      p:=pos(':',list.Strings[index2]);
      n2:=StrToInt(copy(list.Strings[index2],1,p-1));
      result:=n1-n2;
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
      t:tstringlist;
    begin
      t:=tstringlist.Create;
      t.Add('1:aweqw');
      t.Add('2:asd');
      t.Add('4:adas');
      t.Add('11:asdasd');
      t.Add('15:ewr');
      t.Add('10:sdfsdf');
      t.Add('20:sfsd');
      t.CustomSort(mycomp);
      Memo1.Lines.AddStrings(t);
    end;
      

  4.   

    var
      I : Integer ;
      s                 : string;
      p                 : pchar;
      StringList        : TstringList;
      p1                : pchar;
    begin
      StringList := Tstringlist.create();
      s := '2:牛 4:鸡 1:猪 3:虎 8:猴 3:马';
      p := @s[1];
      p1 := p;
      while p^ <> #0 do
      begin
        if p^ = char(' ') then
        begin
          p^ := char(0);
          Stringlist.add(strpas(p1));
          inc(p);
          p1 := p;
        end;
        inc(p);
      end;
      StringList.sort;
      for I := 0 to StringList.Count - 1 do    // Iterate
        begin
          showmessage(Stringlist.Strings[i]) ;
        end ;    // for
      StringList.free;