TStringListDemo
A string list is particularly useful for sorting items and the loading and saving methods require only a line of code each. We demonstrate these features in program TStringListDemo.
program TStringListDemo; {$APPTYPE CONSOLE} uses SysUtils, Classes; const rainbow : array[1..7] of string =('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'); var StringList : TStringList; i, FoundIndex : integer; Found : Boolean; Colour : string; begin StringList := TStringList.Create; // Add just one string StringList.Add('red'); // Add strings from an array for i := 2 to 7 do StringList.Add(rainbow[i]); // Save the strings to text file StringList.SaveToFile('Rainbow.txt'); // Sort in alphabetical order StringList.Sort; // Output the sorted colours writeln('Colours in alphabetical order:'); for i := 0 to 6 do write(StringList[i],' '); writeln; // Insert string in given position StringList.insert(2, 'grey'); writeln('Colours in alphabetical order after grey inserted at index 2:'); for i := 0 to 7 do write(StringList[i],' '); // Search write(#13#10#13#10'Please enter colour to search for. '); readln(Colour); StringList.Sorted := true; Found := StringList.Find(Colour, FoundIndex); if Found then writeln('Found at (zero-based) index ', FoundIndex) else writeln('Not found'); writeln; // Retrieve the original colours in rainbow order StringList.LoadFromFile('Rainbow.txt'); // Output the colours in rainbow order writeln(#13#10'Colours in rainbow order:'); for i := 0 to 6 do write(StringList[i],' '); writeln; readln; end.