The TStringList class is one of the most frequently used components in Object Pascal. It provides a dynamic, object-oriented way to manage a list of strings, offering functionality far beyond a simple dynamic array of strings.
1. The TStringList Class
The TStringList class is a descendant of TStrings and is primarily used to store and manipulate a list of text lines.
- Unit: Requires the
Classesunit (uses Classes;). - Storage: Stores strings in memory, but can easily load/save data to disk files.
A. Creating and Destroying
Since TStringList is a class, it must be created on the Heap and destroyed using Free (P2.4).
uses Classes;
var
MyList: TStringList;
begin
MyList := TStringList.Create; // Allocate memory
try
// Use the list here
finally
MyList.Free; // Mandatory cleanup
end;
end.
2. Basic List Operations
TStringList provides methods for essential list management:
| Property/Method | Purpose | Example |
Add(S) | Appends the string $S$ to the end of the list. | MyList.Add('New Line'); |
Strings[Index] | Accesses or modifies the string at the zero-based Index. | MyList.Strings[0] := 'First Item'; |
Count | Returns the current number of strings in the list. | Writeln(MyList.Count); |
Clear | Removes all strings from the list. | MyList.Clear; |
Delete(Index) | Removes the string at the specified Index. | MyList.Delete(1); |
IndexOf(S) | Returns the zero-based index of string $S$, or $-1$ if not found. | I := MyList.IndexOf('Target'); |
3. Loading and Saving to Files
TStringList makes reading and writing entire files trivial, automatically handling the file streams internally.
| Method | Purpose | Example |
LoadFromFile(FileName) | Clears the list and loads all lines from the specified file into memory. | MyList.LoadFromFile('log.txt'); |
SaveToFile(FileName) | Writes all strings in the list to the specified file, overwriting the existing content. | MyList.SaveToFile('output.log'); |
Example: Reading a file and printing contents
begin
MyList := TStringList.Create;
try
MyList.LoadFromFile('names.txt');
// Iterate over the list using a for loop
for I := 0 to MyList.Count - 1 do
Writeln(MyList.Strings[I]);
finally
MyList.Free;
end;
end.
4. Name-Value Pairs (TStrings Feature)
One of the most powerful features inherited from the base TStrings class is the ability to handle data in the “Name=Value” format, commonly used for configuration files (INI files) or HTTP headers.
- List Format:
Key1=ValueA,Key2=ValueB, etc.
A. Accessing Name-Value Pairs
| Property | Purpose | Example |
Names[Index] | Returns the Name part of the item at Index. | Writeln(MyList.Names[0]); $\rightarrow$ Key1 |
Values[Name] | Returns the Value associated with the given Name (case-sensitive). If the name doesn’t exist, it returns an empty string. | Writeln(MyList.Values['Key1']); $\rightarrow$ ValueA |
Example: Using Values for config lookup
begin
MyList := TStringList.Create;
try
// Populate the list (LoadFromFile would do this automatically for an INI file)
MyList.Add('AppName=MyProject');
MyList.Add('Port=8080');
// Access the values safely
Writeln('Application: ', MyList.Values['AppName']);
Writeln('Port: ', MyList.Values['Port']);
finally
MyList.Free;
end;
end.
5. Sorting and Object Associations
A. Sorting
TStringList can maintain its strings in sorted order, which is essential for fast lookups.
Sorted: Boolean: A property. Setting this toTrueautomatically keeps the list sorted when items are added.Sortmethod: Manually sorts the list once.
begin
// ... create and add items ...
MyList.Sorted := True;
MyList.Add('Banana'); // Will be inserted in alphabetical order
MyList.Add('Apple');
// ...
end;
B. Object Association
TStringList also allows you to associate a TObject reference with every string in the list using the Objects property.
// Storing a TShape object with the string label 'Circle'
MyList.AddObject('Circle', TCircle.Create);
// Retrieving the object
ShapePtr := MyList.Objects[I] as TShape;
