RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TStringList.Find Method

Locates the index for a string in a sorted list and indicates whether a string with that value already exists in the list.

Pascal
function Find(const S: string; var Index: Integer): Boolean; virtual;
C++
virtual __fastcall Boolean Find(const AnsiString S, int Index);

Use Find to obtain the index in a sorted list where the string S should be added. If the string S, or a string that differs from S only in case when CaseSensitive is false, already exists in the list, Find returns true. If the list does not contain a string that matches S, Find returns false. The index where S should go is returned in the Index parameter. The value of Index is zero-based, where the first string has the index 0, the second string has the index 1, and so on.

Note: Only use Find with sorted lists. For unsorted lists, use the IndexOf method instead.
 

C++ Examples: 

 

/*
This example uses a list box and a label on a form. When the
application runs, a string list object is created and three
strings are added to it. The Find method searches the 
strings to look for a match with the string ‘Flowers’. If
the string is found, all the strings in the string list are
added to the list box, and the index value of the ‘Flowers’
string appears in the caption of the label control.
*/

#include <memory>       //for STL auto_ptr class

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  int Index;
  std::auto_ptr<TStringList> MyList(new TStringList());
  MyList->Add("Animals");
  MyList->Add("Flowers");
  MyList->Add("Ocean");
  MyList->Sort(); // Find will only work on sorted lists
  if (MyList->Find("Flowers", Index))
  {
    ListBox1->Items->AddStrings(MyList.get());
    Label1->Caption = "Flowers has an index value of " + AnsiString(Index);
  }
}

 

Delphi Examples: 

{
This example uses a list box and a label on a form. When the
application runs, a string list object is created and three
strings are added to it. The Find method searches the 
strings to look for a match with the string ‘Flowers’. If
the string is found, all the strings in the string list are
added to the list box, and the index value of the ‘Flowers’
string appears in the caption of the label control.
} 
procedure TForm1.FormCreate(Sender: TObject);
var
  MyList: TStringList;
  Index: Integer;
begin
  MyList := TStringList.Create;
  try
    MyList.Add('Animals');
    MyList.Add('Flowers');
    MyList.Add('Cars');
    MyList.Sort;   { Find will only work on sorted lists! }
    if MyList.Find('Flowers', Index) then
    begin
      ListBox1.Items.AddStrings(MyList);
      Label1.Caption := 'Flowers has an index value of ' + IntToStr(Index);
    end;
  finally
    MyList.Free;
  end;
end; 

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!