Home > Enterprise >  delphi convert set type to array of character
delphi convert set type to array of character

Time:09-08

Currently in a legacy code I have a set which I want to convert to array of string so i can pass this as a parameter for existing method.

  //Existing code to be used and converted
  const
  North = 'F';
  Pay = 'P';
  Lynk = 'L';  
  
  TCharSet = set of AnsiChar;
  MySet: TCharSet = [North, Pay, Lynk];

So my question is how do i convert above set to a array of character? Is this doable?

After doing some research found below code and that seems to have enum used to create a set and using TypeInfo to convert the enum to string.

//**Working code**  

  TMyEnum = (meFirst, meSecond, meThird);
  TMySet = set of TMyEnum;
  
function MySetToString(MySet: TMySet): string;
var
  i: TMyEnum;
begin
  Result := '';
  // one way to iterate
  for i := Low(i) to High(i) do
    if i in MySet then
      Result := Result   GetEnumName(TypeInfo(TMyEnum), Ord(i))   ' ';
end;

// call to above method

  set1 := [meFirst, meSecond, meThird];
  ShowMessage(MySetToString(set1));

Any help really appreciated.

CodePudding user response:

//**Working code**  

TMyEnum = (meFirst, meSecond, meThird);
TMySet = set of TMyEnum;
TStrArr = TArray<STRING>;

function MySetToStrings(MySet: TMySet): TStrArr;
var
  i: TMyEnum;
begin
  SetLength(Result,0);
  // one way to iterate
  for i := Low(i) to High(i) do
    if i in MySet then
      Result := Result   [GetEnumName(TypeInfo(TMyEnum), Ord(i))]
end;

// call to above method

var set1 : TMySet;
var arr : TStrArr;
var s : String;

set1 := [meFirst, meSecond, meThird];
arr := MySetToStrings(set1);
for s in arr do ShowMessage(s);

UPDATE (after changed question):

TYPE TCharSet = SET OF AnsiChar;
TYPE TCharArr = TArray<AnsiChar>;

FUNCTION CharSetToCharArr(CONST CharSet : TCharSet) : TCharArr;
  VAR
    C : AnsiChar;

  BEGIN
    SetLength(Result,0);
    FOR C IN CharSet DO Result:=Result [C]
  END;

Your MySet will return this:

CharSetToCharArr(MySet) = ['F','L','P']

ie. a character array containing 3 elements, 'F', 'L' and 'P' in that order (they will always be in ANSI Ordinal order, as sets have no concept of "order").

CodePudding user response:

You can convert each element of the Set to a Char, using Char function. So the code could be something like this:

procedure TForm1.Button1Click(Sender: TObject);
type
  TCharSet = set of AnsiChar;
const
  North = 'F';
  Pay = 'P';
  Lynk = 'L';
var
  MySet: TCharSet;
  myArr: Array of Char;
  c: AnsiChar;
  i: Integer;
begin
  MySet := [North, Pay, Lynk];

  i := 0;
  for c in MySet do
  begin
    SetLength(myArr, Length(myArr) 1);
    myArr[i] := Char(c);
    i := i   1;
  end;

  for i := 0 to Length(myArr)-1 do
    ShowMessage(myArr[i]);
end;
  • Related