Adding and Sorting Strings

From RAD Studio
Jump to: navigation, search

Go Up to How To Build VCL Forms Applications


Creating this VCL application consists of the following steps:

  1. Create a VCL Form with Button, Label, and TListBox controls.
  2. Write the code to add and sort strings.
  3. Run the application.

To create a VCL Form with Button, Label, and ListBox controls

  1. Choose File > New > Other > Delphi Projects or C++Builder Projects and double-click the VCL Forms Application icon. The VCL Forms Designer displays.
  2. From the Standard category of the Tool Palette, place a TButton, TLabel, and TListBox component on the form.

To write the copy stream procedure

  1. Select Button1 on the form.
  2. 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.
  3. For Delphi, place the cursor before the begin reserved word and press ENTER. This creates a new line above the code block.
  4. Type the following variable declarations:

Delphi:

var
  MyList: TStringList;
  Index: Integer;

C++:

TStringList *MyList;
int Index;
  1. 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

  1. Save your project files; then choose Run > Run to build and run the application. The form displays with the controls.
  2. 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.

See Also