如何?以下排序的演算法 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;