delphi2007 教程

delphi2007 教程

首页 新随笔 联系 聚合 管理
  1013 Posts :: 0 Stories :: 28 Comments :: 0 Trackbacks
如何实现以下排序的算法 Delphi / Windows SDK/API
http://www.delphi2007.net/DelphiBase/html/delphi_20061218161948124.html
有类似如下一字符串:“2:牛   4:鸡   1:猪   3:虎   8:猴   3:马”如何实现按生肖前面的数值从大小到的顺序排列,即得到如下字串:“8:猴   4:鸡   3:虎   3:马   2:牛   1:猪”

放到TStringList里,   调用Sort方法

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

order   by....

这种方法不行,11   排在了2的后面。   不行。

我的思路,先分解出来,再排序,再重组  
  按你那种格式的话,就截取字符串,5个一截(最后一个是4个),最多截12次  
  就可以得到  
  2:牛  
  4:鸡  
  1:猪  
  ...  
  然后可以字符串直接比较排序了,最后重组字符串  
   
   
 

喔,不行,然后再分解一次,从后往前截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;  
 

我的意思是先把它们排好,然后付值,按照1234…………,再进行排序就可以了,

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;  
 

posted on 2008-10-14 16:35 delphi2007 阅读(144) 评论(0)  编辑 收藏 引用
只有注册用户登录后才能发表评论。