Identifying a String as a Pascal name

0

I have 50 array type variables and I have a method that will receive a String containing a name from an existing variable. I would like to know what is the ideal way to identify the value of the String received as one of the 50 vari- ables declared in the program.

Here is one of 50 variant nomenclatures:

var
x:array[1..4] of String;

Here is the method:

procedure IdentificarVariavel(s:String); 
begin
     //
     // tratar o valor da String s recebida como váriavel x;
     //
end;

I need to treat the value of String s as a variable. OBS: would not like to create a case.

    
asked by anonymous 29.10.2014 / 14:14

1 answer

2

Even though there is a challenge (which I highly doubt) that serializes local identifiers in String , the proposal below is simpler and (in my opinion) more elegant.

interface
uses Vcl.Dialogs, Classes; 

type
    TMyArray = array[0..4] of String;
    TStringHash = class
    private
        FKeys : TStringList;
        FValues : Array of TMyArray;
        function GetContent(Key: String; Index : Integer): String;
        procedure SetContent(Key : String; Index : Integer; Value: String);
    public
        property Contents[Key : String; Index : Integer] : String read GetContent write SetContent; Default;
        constructor Create;
        function Count : Integer;
    end;

implementation

constructor TStringHash.Create;
begin
    inherited;
    FKeys := TStringList.Create;
    FKeys.Add('');
    SetLength(FValues, 1);
    FValues[0][0] := '';
end;

function TStringHash.Count: Integer;
begin
    Result := FKeys.Count;
end;

function TStringHash.GetContent(Key: String; Index : Integer) : String;
var
    I : Integer;
begin
    Result := '';
    I := FKeys.IndexOf(Key) ;
    if I > -1 then
        Result := FValues[I][Index];
end;

procedure TStringHash.SetContent(Key : String; Index : Integer; Value: String);
var
    I : Integer;
begin
    I := FKeys.IndexOf(Key) ;
    if I > -1 then
        FValues[I][Index] := Value
    else
    begin
        SetLength(FValues, Length(FValues) + 1);
        FValues[Length(FValues) - 1][Index] := Value;
        FKeys.Add(Key);
    end;
end;

To use, just instantiate TStringHash with the following line MinhaHash := TStringHash.Create; .

And to manipulate values use: Valor := MinhaHash['NomeVar', 0]; and MinhaHash['NomeVar', 0] := Valor; .

Example

Create a Test.dpr file. Double-click (assuming you have Delphi installed) and after Delphi opens the file paste ( content ) and compile (F9) .

    
04.11.2014 / 16:19