// Common tstringlist methods and attributes:
VaR
List: tstringlist;
I: integer;
Begin
List: = tstringlist. Create;
List. Add ( 'Strings1' ); {Add}
List. Add ( 'Strings2' );
List. Exchange ( 0 , 1 ); {Replacement}
List. insert ( 0 , 'Strings3' ); {Insert}
I: = List. indexof ( 'Strings1' ); {Location of the first appearance}
List. Sort; {Sorting}
List. Sorted: = true; {Specified sorting}
List. count; {Total}
List. text; {Text set}
List. Delete ( 0 ); {Delete, 0 is the first data}
List. loadfromfile ( 'C: \ tmp.txt' ); {Open}
List. savetofile ( 'C: \ tmp.txt' ); {Save}
List. Clear; {Empty}
List. Free; {Release}
End ;
// Read the string
VaR
List: tstringlist;
Begin
List: = tstringlist. Create;
List. commatext: = 'Aaa, BBB, CCC, DDD' ;
// Equivalent to: list. text: = 'aaa' + #13 #10 + 'bbb '+ #13 # 10' + 'ccc' + '#13 # 10' + 'ddd ';
Showmessage (inttostr (list. Count )); // 4
Showmessage (list [ 0 ]); // Aaa
List. Free;
End ;
// delimiter replacement
var
List: tstringlist;
begin
List: = tstringlist. create;
list. delimiter: = '|' ;
list. delimitedtext: = 'aaa | BBB | CCC | DDD ' ;
Showmessage (inttostr (list. Count ));// 4
Showmessage (list [0]);// Aaa
List. Free;
End;
// similar hash table operation method
var
List: tstringlist;
begin
List: = tstringlist. create;
List. Add ('Aaa = 8080');
List. Add ('Bbb = 8080');
List. Add ('Ccc = 66661');
List. Add ('Ddd = 66661');
Showmessage (list. Names [ 1 ]); // Bbb
Showmessage (list. valuefromindex [ 1 ]); // 222
Showmessage (list. Values [ 'Bbb' ]); // 222
// Valuefromindex can be assigned a value:
List. valuefromindex [ 1 ]: = '2' ;
Showmessage (list [ 1 ]); // BBB = 2
// You can assign values through values:
List. Values [ 'Bbb' ]: = '22' ;
Showmessage (list [ 1 ]); // BBB = 22
List. Free;
End ;
// Avoid repeated values
VaR
List: tstringlist;
Begin
List: = tstringlist. Create;
List. Add ('Aaa');
List. Sorted: = true;// Specify the sorting first
List. Duplicates: = dupignore;// Give up if there is a duplicate value
List. Add ('Aaa');
Showmessage (list. Text ); // Aaa
// Duplicates has three optional values:
// Dupignore: give up;
// Dupaccept: end;
// Duperror: an error is prompted.
List. Free;
End ;
// sort and reverse sort
{sorting function}
function desccomparestrings (list: tstringlist; index1, index2: integer): integer;
begin
result: =-ansicomparetext (list [index1], list [index2]);
end ;
procedure tform1.button1click (Sender: tobject);
var
List: tstringlist;
begin
List: = tstringlist. create;
List. Add ('Bbb');
List. Add ('Ccc');
List. Add ('Aaa');
// Unordered
Showmessage (list. Text ); // Bbb ccc aaa
// Sort
List. Sort;
Showmessage (list. Text ); // Aaa bbb ccc
// Inverted sorting
List. customsort (desccomparestrings ); // Call the sorting Function
Showmessage (list. Text ); // Ccc bbb aaa
// Assume that:
List. Sorted: = true;
List. Add ( '123' );
List. Add ( '000' );
List. Add ( 'Zzz' );
Showmessage (list. Text ); // 000999 aaa bbb ccc zzz
End ;