Watch, Follow, &
Connect with Us

Please visit our new home
community.embarcadero.com.


Welcome, Guest
Guest Settings
Help

Thread: Sorting contents of a TStringlist not as per ASCII values


This question is answered.


Permlink Replies: 1 - Last Post: Oct 30, 2017 7:48 AM Last Post By: Lajos Juhasz Threads: [ Previous | Next ]
Allan Fernandes

Posts: 76
Registered: 9/30/00
Sorting contents of a TStringlist not as per ASCII values  
Click to report abuse...   Click to reply to this thread Reply
  Posted: Oct 30, 2017 2:10 AM
Hi,

Sorting contents of a TStringlist I get following result.
In the sample below Each line has a significant character followed by Space and the respective ASCII value.

Result:
- 45
# 35
; 59
_ 95
1 49
2 50
A 65
a 97
B 66
b 98
Lajos Juhasz

Posts: 801
Registered: 3/14/14
Re: Sorting contents of a TStringlist not as per ASCII values
Correct
Click to report abuse...   Click to reply to this thread Reply
  Posted: Oct 30, 2017 7:48 AM   in response to: Allan Fernandes in response to: Allan Fernandes
Allan Fernandes wrote:

Hi,

Sorting contents of a TStringlist I get following result.
In the sample below Each line has a significant character followed by
Space and the respective ASCII value.

Result:
- 45
# 35
; 59
_ 95
1 49
2 50
A 65
a 97
B 66
b 98

This question belongs to embarcadero.public.delphi.vcl.component.using.

What you wrote is correct and you can confirm by reading the help:

Call Sort to sort the strings in a list that has the Sorted property
set to false. String lists with the Sorted property set to true are
automatically sorted.
Note:  Sort uses AnsiCompareStr to sort the strings when CaseSensitive
is true and AnsiCompareText when CaseSensitive is false. To provide
your own comparison operator instead, use the CustomSort method.


But we cannot do you want case sensitive sort or not. In the last
sentence there is the mention of the CustomSort. If you're not after
case insensitive sort you have to use CustomSort that expects a
function that will compare the list elements during the sorting:

TStringListSortCompare = function (List: TStringList; Index1, Index2:
Integer): Integer;

You can google for an example
(https://stackoverflow.com/questions/15257746/custom-sort-method-in-delphi-to-sort-list-of-strings):

function compare(List: TStringList; Index1, Index2: Integer): Integer;
var
  n1, n2: integer;
begin
  n1 := StrToInt(Copy(List[Index1], 3, Length(List[Index1]) - 6));
  n2 := StrToInt(Copy(List[Index2], 3, Length(List[Index2]) - 6));
  result := n1 - n2;
end;
 
var
  sl: TStringList;
 
procedure AddAndSort;
begin
  sl := TStringList.Create;
  sl.Add('a_1.xml');
  sl.Add('a_20.xml');
  sl.Add('a_10.xml');
  sl.Add('a_2.XML');
  sl.CustomSort(compare);
end;
Legend
Helpful Answer (5 pts)
Correct Answer (10 pts)

Server Response from: ETNAJIVE02