下面是一些示例代碼,將讓你實驗排序。它在每行上使用文本值和數字,用製表符分隔(#9
)。每個按鈕點擊處理程序的開始處都有代碼,可將文本重置爲相同的起始值,以便您可以看到效果。所述第一按鈕(btnNameSort
)排序通過使用標準TStringList.Sort
文本值,和第二(btnScoreSort
)排序通過使用TListSortCompare
自定義排序功能的數值。
// Simply uses TStringList.Sort to sort in the default (alpha) order
procedure TForm1.btnNameSortClick(Sender: TObject);
var
SL: TStringList;
begin
InitMemoLines;
SL := TStringList.Create;
try
Memo1.Lines.BeginUpdate;
try
SL.Assign(Memo1.Lines);
SL.Sort;
Memo1.Lines.Assign(SL);
finally
Memo1.Lines.EndUpdate;
end;
finally
SL.Free;
end;
end;
// Sorts by extracting the text after the tab character on the lines
// being compared, converting to numbers, and comparing the numbers.
// Called by using SL.CustomSort in the btnScoreSortClick event
// below.
//
// NOTE: Will obviously fail if the lines don't contain a tab, or
// if the content after the tab can't be converted to a numeric.
// Neither of those cases is handled here for brevity.
function NumberedListSort(List: TStringList; Index1, Index2: Integer): Integer;
var
Line1, Line2: string;
Num1, Num2: Integer;
begin
Line1 := List[Index1];
Line2 := List[Index2];
Num1 := StrToInt(Copy(Line1, Pos(#9, Line1) + 1, 255));
Num2 := StrToInt(Copy(Line2, Pos(#9, Line2) + 1, 255));
Result := Num1 - Num2;
end;
// Calls NumberedListSort to sort by the numbers on the right end
// of each line in the memo
procedure TForm1.btnScoreSortClick(Sender: TObject);
var
SL: TStringList;
begin
InitMemoLines;
SL := TStringList.Create;
try
Memo1.Lines.BeginUpdate;
try
SL.Assign(Memo1.Lines);
SL.CustomSort(NumberedListSort);
Memo1.Lines.Assign(SL);
finally
Memo1.Lines.EndUpdate;
end;
finally
SL.Free;
end;
end;
// Calls InitMemoLines to set the starting content of the memo
procedure TForm1.FormCreate(Sender: TObject);
begin
InitMemoLines;
end;
// Generates content of memo
procedure TForm1.InitMemoLines;
var
i: Integer;
begin
Memo1.Lines.Clear;
for i := 1 to 10 do
Memo1.Lines.Append(Format('Line ' + Chr(90 - i) + #9 + ' %d', [i]));
end;
我認爲你應該看看創建一個數據對象和排序數據對象。然後你應該將數據對象(已經排序)打印到字符串列表中。你陷入了只使用內置數據類型(特別是字符串)的「字符串類型」壞習慣,你應該考慮創建自己的記錄或類。 –