How to wash / check a string to assign it to a component name?

I have a submenu listing departments. Behind this, each department has an action, which is given the name "actPlan" + department.name.

Now I understand that it was a bad idea, because the name can contain any strange character in the world, but action.name cannot contain international characters. Obviously, the Delphi IDE itself calls some method to verify that the string name is correct. Does anyone know more about this?

I also have an idea to use

Action.name := 'actPlan' + department.departmentID;

instead of this. The advantage is that departmentID is a well-known format "xxxxx-x" (where x is 1-9), so I only need to replace the "-" with, for example, an underscore. The problem here is that those old actionnames are already saved in a personal text file. These will be exceptions if I suddenly switch from using department names to IDs.

I could, of course, first have an exception, and then call a method in which the search replaces this text file with the correct data and reloads it.

So basically I am looking for the most elegant and future method to solve this problem :) I am using D2007.

+3
source share
2 answers

IsValidIdent SysUtils, , , - .

, , , , , .

. , , - , , , .

function MakeValidIdent(const s: string): string;
var
  len: Integer;
  x: Integer;
  c: Char;
begin
  SetLength(Result, Length(s));
  x := 0;
  for c in s do
    if c in ['A'..'Z', 'a'..'z', '0'..'9', '_'] then begin
      Inc(x);
      Result[x] := c;
    end;
  SetLength(Result, x);
  if x = 0 then
    Result := '_'
  else if Result[1] in ['0'..'9'] then
    Result := '_' + Result;
  // Optional uniqueness protection follows. Choose one.
  Result := Result + IntToStr(Checksum(s));
  Result := Result + GetDepartment(s).ID;
end;

Delphi 2009 in CharInSet. (Unicode- Delphi-.) Delphi 8 in for s.

+7

// See SysUtils.IsValidIdent:
function MakeValidIdent(const AText: string): string;
const
  Alpha = ['A'..'Z', 'a'..'z', '_'];
  AlphaNumeric = Alpha + ['0'..'9'];

  function IsValidChar(AIndex: Integer; AChar: Char): Boolean;
  begin
    if AIndex = 1 then
      Result := AChar in Alpha
    else
      Result := AChar in AlphaNumeric;
  end;

var
  i: Integer;
begin
  Result := AText;
  for i := 1 to Length(Result) do
    if not IsValidChar(i, Result[i]) then
      Result[i] := '_';
end;

Pascal . FindUniqueName Classes.pas MakeValidIdent.

+5

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


All Articles