Delphi-使用混合值对TStringList进行排序-整数和字符串 [英] Delphi - sorting TStringList with mixed values - integer and string

查看:232
本文介绍了Delphi-使用混合值对TStringList进行排序-整数和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对带有混合值的TStringList进行排序时遇到了一些问题.类似于:

I have a little problem with sorting TStringList with mixed values. Its something like:

7567533575乔
1543779744安
9757462323杰克
6999966578 Stef

7567533575 Joe
1543779744 Ann
9757462323 Jack
6999966578 Stef

,我需要对该列表进行排序才能看到:

and I need to sort this list to see:

1543779744安
6999966578 Stef
7567533575乔
9757462323杰克

1543779744 Ann
6999966578 Stef
7567533575 Joe
9757462323 Jack

我可以用大约3倍的循环(使用字符串修剪和一个数组)来完成此操作.但这是非常la脚的解决方案……我想,有人为此提供了最好的代码.我不了解CustomSort ...嗯.请帮帮我.

I can do this with about 3x for loops, with string trim and one array. But it is very lame solution... I guess, someone have best code for this. I dont understand CustomSort... ehh. Please, help me.

  • 我使用Delphi 10.

推荐答案

使用CustomSort()是正确的解决方案.只需将其传递给一个函数即可解析并比较2个输入字符串,返回:

Using CustomSort() is the correct solution. Simply pass it a function that parses and compares 2 input strings, returning:

  • <如果第一个字符串应该出现在第二个字符串之前,则为0.

  • < 0 if the 1st string should appear before the 2nd string.

0,如果2个字符串相等"并且其中一个字符串可以出现在另一个字符串之前.

0 if the 2 strings are "equal" and either string can appear before the other.

>如果第二个字符串应该出现在第一个字符串之前,则为0.

> 0 if the 2nd string should appear before the 1st string.

function MySortFunc(List: TStringList; Index1, Index2: Integer): Integer;
var
  Value1, Value2: Int64;
  S: string;
begin
  S := List[Index1];
  Value1 := StrToInt64(Copy(S, 1, Pos(' ', S)-1));
  S := List[Index2];
  Value2 := StrToInt64(Copy(S, 1, Pos(' ', S)-1));
  if Value1 < Value2 then
    Result := -1
  else if Value2 < Value1 then
    Result := 1
  else
    Result := 0;
end;

MyStringList.CustomSort(MySortFunc);

这篇关于Delphi-使用混合值对TStringList进行排序-整数和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆