RAD Studio |  |

Adding and Sorting Strings
See Also
Collapse All

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 FileNewOtherDelphi 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:

Copy Code

    var
      MyList: TStringList;
      Index: Integer;

Copy Code

    TStringList *MyList;
    int Index;

1. Insert the cursor within the code block, and type the following code:

Copy Code

    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;

Copy Code

    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 RunRun 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

VCL Overview

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