Delphi Tstringlist Usage Detailed.
Tstringlist Common Methods and properties:
varlist:tstringlist; I:integer;beginList:= Tstringlist.Create; List.add ('STRINGS1');{Add}List.add ('STRINGS2'); List.exchange (0,1);{Displacement}List.insert (0,'STRINGS3');{Insert}I:= List.indexof ('STRINGS1');{the first occurrence of the position}List.sort; {Sort}list.sorted:= True;{Specify sort}List.count; {Total}List.text; {Text Collection}List.delete (0);{Delete, 0 is the first data}List.loadfromfile ('C:/tmp.txt');{Open}List.savetofile ('C:/tmp.txt');{Save}list.clear; {Clear}List.free; {Release}End;
Read in string:
var list:tstringlist; begin List: = tstringlist. create ; List.commatext: = " aaa,bbb,ccc,ddd " ; // ShowMessage (IntToStr (List.count)); // 4 showmessage (list[0 ]); // aaa List.free; end ;
Displacement delimiter:
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 ;
A similar hash table operation method:
varlist:tstringlist;beginList:= Tstringlist.Create; List.add ('aaa=111'); List.add ('bbb=222'); List.add ('ccc=333'); List.add ('ddd=444'); ShowMessage (list.names[1]);//BBBShowMessage (list.valuefromindex[1]);//222ShowMessage (list.values['BBB']);//222//Valuefromindex can be assigned values:list.valuefromindex[1] :='2'; ShowMessage (list[1]);//bbb=2//values can be assigned by:list.values['BBB'] :=' A'; ShowMessage (list[1]);//bbb=22List.free;End;
Avoid duplicate values:
varlist:tstringlist;beginList:= Tstringlist.Create; List.add ('AAA'); List.sorted:= True;//you need to specify a sort firstList.duplicates: = Dupignore;//Discard if duplicate value is foundList.add ('AAA'); ShowMessage (List.text); //AAA//The duplicates has 3 selectable values://Dupignore: Give up;//dupaccept: End;//Duperror: Prompt error.List.free;End;
Sort and reverse sort {sort Function}:
functiondesccomparestrings (list:tstringlist; Index1, Index2:integer): Integer;beginResult:= -Ansicomparetext (List[index1], list[index2]);End;procedureTform1. Button1Click (sender:tobject);varlist:tstringlist;beginList:= Tstringlist.Create; List.add ('BBB'); List.add ('CCC'); List.add ('AAA');//not sortedShowMessage (List.text);//BBB CCC AAA//SortList.sort; ShowMessage (List.text); //AAA BBB CCC//Inverted SortList.customsort (desccomparestrings);//Call sort functionShowMessage (List.text);//CCC BBB AAA//if:list.sorted: =True; List.add ('999'); List.add (' the'); List.add ('zzz'); ShowMessage (List.text); //999 AAA BBB CCC zzzEnd;
Delphi Tstringlist Usage Detailed