How to pass a string variable as TSysCharSet

Is it possible to pass a string as a TSysCharSet variable?

This, of course, does not compile:

var
  AValidChars: SysUtils.TSysCharSet;
  AResult: string;
begin
  // Edit1.Text can contain 0..9 or a..z
  AValidChars := SysUtils.TSysCharSet( [Edit1.Text] );
end;

Thanks Bill

+3
source share
2 answers

No, it is simply not possible to pass a string as TSysCharSet.

However, you can create a TSysCharSet that contains all the characters in the string. This code will do this:

var
  AValidChars: SysUtils.TSysCharSet;
  s: AnsiString;
  i: integer;
begin
  // Edit1.Text can contain 0..9 or a..z
  AValidChars := [];
  s := Edit1.Text;
  for i := 1 to Length(s) do
    Include(AValidChars, s[i]);
end;

If you are not using an earlier version of Delphi, you can also use "for ... in" instead of the loop above:

var
  AValidChars: SysUtils.TSysCharSet;
  c: AnsiChar;
begin
  // Edit1.Text can contain 0..9 or a..z
  AValidChars := [];
  for c in Edit1.Text do
    Include(AValidChars, c);
end;

Note that both code snippets use AnsiString / AnsiChar, since this method will not work with WideString or the Unicode string type introduced with Delphi 2009.

Craig Stuntz, Ken White , , .

+5

Edit1.Text :

'0..9'

:

var 
  AValidChars: SysUtils.TSysCharSet;
  StartChar, EndChar: char;
  c: char;
begin
  StartChar := Edit1.Text[1]; // some validation should be done
  EndChar := Edit1.Text[4];
  AValidChars := [];
  for c := StartChar to EndChar do
    Include(AValidChars, c);
end;

Delphi/Pascal.

Update:

, set:

function StrToSysCharSet(const S: string): TSysCharSet;
var
  Elements: TStringList;
  CurrentElement: string;
  StartChar, EndChar: char;
  c: char;
  i: Integer;
  p: Integer;
  function ReadChar: Char;
  begin
    Result := CurrentElement[p];
    Inc(p);
  end;
  function NextIsDotDot: Boolean;
  begin
    Result := '..' = Copy(CurrentElement, p, 2);
  end;
begin
  Elements := TStringList.Create;
  try
    Elements.CommaText := S;
    Result := [];
    for i := 0 to Elements.Count - 1 do
    begin
      CurrentElement := Trim(Elements[i]);
      p := 1;
      StartChar := ReadChar;
      if NextIsDotDot then
      begin
        Inc(p, 2);
        EndChar := ReadChar;
        for c := StartChar to EndChar do
          Include(Result, c);
      end
      else
        Include(Result, StartChar);
    end;
  finally
    Elements.Free;
  end;
end;

:

S := '0..9, a..z';
AValidChars := StrToSysCharSet(S);

S := '0..9 and a..z';
AValidChars := StrToSysCharSet(AnsiReplaceText(S, ' and ', ', '));

S := '''0''..''9'' and ''a''..''z'''

.

0

Source: https://habr.com/ru/post/1703436/


All Articles