17.12 TStringCollection

The TStringCollection object manages a sorted collection of pascal strings. To this end, it overrides the Compare (614) method of TSortedCollection, and it introduces methods to read/write strings from a stream.

Here is the full declaration of the TStringCollection object:

 TYPE
    TStringCollection = OBJECT (TSortedCollection)
       Function GetItem (Var S: TStream): Pointer; Virtual;
       Function Compare (Key1, Key2: Pointer): Sw_Integer; Virtual;
       Procedure FreeItem (Item: Pointer); Virtual;
       Procedure PutItem (Var S: TStream; Item: Pointer); Virtual;
    END;
    PStringCollection = ^TStringCollection;

TStringCollection.GetItem

Declaration:
Function TStringCollection.GetItem (Var S: TStream): Pointer; Virtual;
Description:
GetItem reads a string from the stream S and returns a pointer to it. It doesn’t insert the string in the collection.

This method is primarily introduced to be able to load and store the collection from and to a stream.

Errors:
The errors returned are those of TStream.ReadStr (569).
See also:
PutItem (621)

TStringCollection.Compare

Declaration:
Function TStringCollection.Compare (Key1, Key2: Pointer): Sw_Integer; Virtual;
Description:
TStringCollection overrides the Compare function so it compares the two keys as if they were pointers to strings. The compare is done case sensitive. It returns the following results:
-1
if the first string is alphabetically earlier than the second string.
0
if the two strings are equal.
1
if the first string is alphabetically later than the second string.
Errors:
None.
See also:
TSortedCollection.Compare (614)

Listing: objectex/ex37.pp


Program ex37;

{ Program to demonstrate the TStringCollection.Compare method }

Uses Objects;

Var C : PStringCollection;
    S : String;
    I : longint;

begin
  Randomize;
  C:=New(PStringCollection,Init(120,10));
  C^.Duplicates:=True; { Duplicates allowed }
  Writeln ('Inserting 100 records at random places.');
  For I:=1 to 100 do
    begin
    Str(Random(100),S);
    S:='String with value '+S;
    C^.Insert(NewStr(S));
    end;
  For I:=0 to 98 do
    With C^ do
    If Compare (At(i),At(I+1))=0 then
      Writeln ('Duplicate string found at position ',i);
  Dispose(C,Done);
end.

TStringCollection.FreeItem

Declaration:
Procedure TStringCollection.FreeItem (Item: Pointer); Virtual;
Description:
TStringCollection overrides FreeItem so that the string pointed to by Item is disposed from memory.
Errors:
None.
See also:
TCollection.FreeItem (605)

TStringCollection.PutItem

Declaration:
Procedure TStringCollection.PutItem (Var S: TStream; Item: Pointer); Virtual;
Description:
PutItem writes the string pointed to by Item to the stream S.

This method is primarily used in the Load and Store methods, and should not be used directly.

Errors:
Errors are those of TStream.WriteStr (572).
See also:
GetItem (620)