Page 1 of 1

Removing duplicte chars

PostPosted: September 23rd, 2012, 10:08 am
by Zvikai
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.

Re: Removing duplicte chars

PostPosted: September 23rd, 2012, 12:00 pm
by Kambiz
What do you mean with duplicate characters? Could you please give an example?

Re: Removing duplicte chars

PostPosted: September 23rd, 2012, 2:17 pm
by Zvikai
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.

Re: Removing duplicte chars

PostPosted: September 24th, 2012, 7:13 pm
by Kambiz
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;