Show a count of duplicate strings

delphi United States
  • 11 years ago

    Hi

    Help :)  Can someone show me (an easy way) how to list (in a listbox or stringlist etc.) a count of duplicate strings? 

    So far, I have looped through and added the strings to a listbox from a stringlist and the result i'm after is to show the list in the format in the 2nd column below (showing the number of duplicate strings). 

    Listbox1                  Listbox2

    examplea                 examplea 2

    exampleb                 exampleb 3

    examplea                 examplec

    examplec

    exampleb

    exampleb

    Hope that makes sense and any help will be greatly appreciated :|

    Ellen

    (Junior :))

     

     

  • 11 years ago

    OK - first things first, I'm remote from my Delphi compiler, so this is off the top of my head...you may need to fix a couple of compile time typos :-)

    You'll need two TListBox components on a form and the following code behind a button:


    begin

      ListBox1.Sorted := true;

      count := 1;

      lastString := '';

      for i:=0 to ListBox1.Items.Count-1 do begin
        thisString := ListBox1.Items[i];

        if thisString = lastString then
          count := count + 1
        else
          if lastString <> '' then begin
             ListBox2.Items.Add(lastString + ' ' + IntToStr(count));
             count := 1;
          end;





          // Added

          lastString := thisString;
      end;

      if count > 1 then
        ListBox2.Items.Add(lastString + ' ' + IntToStr(count));

    end;

    The key is to sort the listbox, then look for duplicate strings that are adjacent to each other.

    Anyway, it's not the best way of weeding out duplicates, but it should give you enough to get you started.

    HTH

  • 11 years ago

    Hi,

    Thanks very much for that, it works (it seems i had the right idea, but just went around in circles :) )

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.”