Convert strings to character sets and vice versa #234

The following code converts strings into character sets and vice-versa.

Note: this code works only for non-Unicode versions of Delphi (i.e. Delphi 2007 and earlier) where string = AnsiString. For Delphi 20009 and later use TSysCharSet instead of TCharSet and replace all occurrences of string with AnsiString.

type
  TCharSet = set of char;
 
function StringToCharSet(const Txt: string): TCharSet;
var
  CP: PChar;
begin
  Result := [];
  if Txt = '' then
    Exit;
  CP := PChar(Txt);
  while CP^ <> #0 do 
  begin
    Include(Result, CP^);
    Inc(CP);
  end;
end;
 
function CharSetToString(const Chars: TCharSet): string;
var
  I: Integer;
begin
  Result := '';
  for I := 0 to 255 do
    if Chr(I) in Chars then
      Result := Result + Chr(I);
end;
Original resource:
Author: Thomas Morschhaeuser
Contributor: Thomas Morschhaeuser
Added: 2014/05/22
Last updated: 2014/05/29