Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Arrays in Innosetup

I am trying to get a particular integer after a sub string in InnoSetup in a line. There are Trim, TrimLeft, TrimRight functions but no substring extraction functions.

Example :

line string:    2345
line another string:     3456

I want to extract "2345" and "3456".

I am loading the file content in a array but can't get it de-referenced by array[count][char_count].

like image 776
Raulp Avatar asked Feb 13 '23 15:02

Raulp


1 Answers

I would load the input file to a TStrings collection and iterate it line by line. For each line I would find a ":" char position and from this position I would copy the string which I would finally trim. In steps:

1. line string:    2345
2.     2345
3. 2345

Now remains to convert such string to an integer and add it to the final collection. Since you've shown an empty line in your file sample, and since you didn't said if this format will always be fixed, let's convert this string in the safe way. Inno Setup provides for this safe conversion just one function, the StrToIntDef function. This function however requires a default value, which is returned when the conversion fails and so you will have to pass to its call a value, which you'll never expect in your file. In the following example I chose -1, but you can replace it with any other value that you never expect in your input file:

[Code]
type
  TIntegerArray = array of Integer;

procedure ExtractIntegers(Strings: TStrings; out Integers: TIntegerArray);
var
  S: string;
  I: Integer;
  Value: Integer;
begin
  for I := 0 to Strings.Count - 1 do
  begin
    // trim the string copied from a substring after the ":" char
    S := Trim(Copy(Strings[I], Pos(':', Strings[I]) + 1, MaxInt));
    // try to convert the value from the previous step to integer;
    // if such conversion fails, because the string is not a valid
    // integer, it returns -1 which is treated as unexpected value
    // in the input file
    Value := StrToIntDef(S, -1);
    // so, if a converted value is different from unexpected value,
    // add the value to the output array
    if Value <> -1 then
    begin
      SetArrayLength(Integers, GetArrayLength(Integers) + 1);
      Integers[GetArrayLength(Integers) - 1] := Value;
    end;
  end;
end;

procedure InitializeWizard;
var
  I: Integer;
  Strings: TStringList;
  Integers: TIntegerArray;
begin
  Strings := TStringList.Create;
  try
    Strings.LoadFromFile('C:\File.txt');

    ExtractIntegers(Strings, Integers);
    for I := 0 to GetArrayLength(Integers) - 1 do
      MsgBox(IntToStr(Integers[I]), mbInformation, MB_OK);
  finally
    Strings.Free;
  end;
end;
like image 188
TLama Avatar answered Mar 16 '23 11:03

TLama