Adding and Sorting Strings
Go Up to How To Build Windows VCL Applications
Creating this VCL application consists of the following steps:
- Create a VCL Form with Button, Label, and TListBox controls.
- Write the code to add and sort strings.
- Run the application.
To create a VCL Form with Button, Label, and ListBox controls
- Choose File > New > Windows VCL Application - Delphi or Windows VCL Application - C++ Builder.
- From the Standard category of the Tool Palette, place a TButton, TLabel, and TListBox component on the form.
To write the copy stream procedure
- Select Button1 on the form.
- In the Object Inspector, double-click the OnClick action on the Events tab. The Code Editor displays, with the cursor in the TForm1.Button1Click event handler block.
- For Delphi, place the cursor before the begin reserved word and press ENTER. This creates a new line above the code block.
- Type the following variable declarations:
Delphi:
var
  MyList: TStringList;
  Index: Integer;
C++:
TStringList *MyList;
int Index;
- Insert the cursor within the code block, and type the following code:
Delphi:
MyList := TStringList.Create;
try
  MyList.Add('Animals');
  MyList.Add('Flowers');
  MyList.Add('Cars');
  MyList.Sort;
    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;
C++:
MyList = new TStringList();
try {
  MyList->Add( "Animals" );
  MyList->Add( "Flowers" );
  MyList->Add( "Cars" );
  MyList->Sort();
  if( MyList->Find( "Flowers", Index ) {
    ListBox1->Items->AddStrings( MyList );
    Label1->Caption = "Flowers has an index of " +
                        IntToStr( Index );
  }
} __finally {
  MyList->Free();
}
Note:  Find will only work on sorted lists. Use IndexOf on unsorted lists.
To run the application
- Save your project files; then choose Run > Run to build and run the application. The form displays with the controls.
- Click the Button. The strings 'Animals', 'Cars', and 'Flowers' display alphabetically in a list in the ListBox. The Label caption displays the message string:
- Flowers has an index value of 2.