Removing duplicte chars

Please discuss general Delphi programming topics here.

Removing duplicte chars

Postby Zvikai » September 23rd, 2012, 10:08 am

Hi,

How can I remove any duplicates from a string var ?
I need auto cleaning the string from any kinde of duplicate characters.

Thanks,
Z.
Zvikai
Active Member
Active Member
 
Posts: 7
Joined: September 24th, 2008, 10:47 am

Re: Removing duplicte chars

Postby Kambiz » September 23rd, 2012, 12:00 pm

What do you mean with duplicate characters? Could you please give an example?
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm

Re: Removing duplicte chars

Postby Zvikai » September 23rd, 2012, 2:17 pm

Hi,

If the string is 'abca1231', I need the result to be 'abc123'.
Tha string is a var so I don't know what characters it will contain (user input), I just need to keep only one char of a kind.

Thanks,
Z.
Zvikai
Active Member
Active Member
 
Posts: 7
Joined: September 24th, 2008, 10:47 am

Re: Removing duplicte chars

Postby Kambiz » September 24th, 2012, 7:13 pm

Here is a solution:

Code: Select all
function RemoveDuplicateChars(const S: String): String;
var
  AlreadyVisited: array[#0..High(Char)] of Boolean;
  I: Integer;
begin
  FillChar(AlreadyVisited, SizeOf(AlreadyVisited), 0);
  Result := '';
  for I := 1 to length(S) do
  begin
    if not AlreadyVisited[S[I]] then
    begin
      Result := Result + S[I];
      AlreadyVisited[S[I]] := True;
    end;
  end;
end;
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2429
Joined: March 7th, 2003, 7:10 pm


Return to Delphi Programming

Who is online

Users browsing this forum: No registered users and 0 guests

cron