下面是一些示例代码,将让你实验排序。它在每行上使用文本值和数字,用制表符分隔(#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;
我认为你应该看看创建一个数据对象和排序数据对象。然后你应该将数据对象(已经排序)打印到字符串列表中。你陷入了只使用内置数据类型(特别是字符串)的“字符串类型”坏习惯,你应该考虑创建自己的记录或类。 –