Link to home
Start Free TrialLog in
Avatar of kh420
kh420

asked on

Counting Strings

Hey,
First of all I apologize for my English. It is not my first language.
I am new with Delphi.
I want to make a program that counts duplicated strings in a ListBox.
My program has a 2 component a button and a List box. If I push the button it must count how many strings or dabble and show it in a messageBox.
can somebody help me plz?

PS: I have tried with Array and For statement, but I didnt succeed.
Avatar of andrewjb
andrewjb
Flag of United Kingdom of Great Britain and Northern Ireland image

If speed isn't a problem:

[Listbox called 'LB', Label called 'Label1']

procedure CountDoubles;
var
  lCount : integer;
  lIndex : integer;
  lPos   : integer;
begin
  lCount := 0;

  for lIndex := LB.Items.Count - 1 downto 1 do
  begin
    lPos := LB.Items.Find( LB.Items[lIndex] );
    if ( lPos >= 0 ) and ( lPos < lIndex ) then
    begin
      Inc( lCount );
    end;
  end;

  Label1.Caption = IntToStr(lCount) + ' duplicates';
end;

   
ooopss... 'Find' should be 'IndexOf'

and

after Label1.Caption

it should be

:=

instead of

=
ASKER CERTIFIED SOLUTION
Avatar of mocarts
mocarts

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kretzschmar
my version :-))

unit checkfor_duplicates_u;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function checkfor_dub_strings(AStringList : TStrings) : Integer;
var
  sl : TStringList;
begin
  result := 0;  //pre-init
  sl := TStringList.Create;
  try
    sl.Sorted := true;
    sl.Duplicates := dupIgnore;
    sl.Assign(AStringList);
    result := AStringList.Count - sl.Count;
  finally
    sl.Free;
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  showmessage('There are '+inttostr(checkfor_dub_strings(ListBox1.Items))+' Duplicate Entries');
end;

end.

meikl ;-)