Search code examples
inno-setuppascalscript

Inno Setup - Pad a string to a specific length with zeros


Here's what my code currently looks like:

var
  Page: TInputQueryWizardPage;

procedure IDKeyPress(Sender: TObject; var Key: Char);
var
  KeyCode: Integer;
begin
  KeyCode := Ord(Key);
  if not ((KeyCode = 8) or ((KeyCode >= 48) and (KeyCode <= 57))) then
    Key := #0;
end;

Procedure InitializeWizard();
Begin
Page := CreateInputQueryPage(blahblah);
  Page.Add('Profile ID:', False);
  Page.Edits[0].MaxLength := 16;
  Page.Edits[0].OnKeyPress := @IDKeyPress;
  Page.Values[0] := '0000000000000000';
End;

procedure WriteUserInput;
var
A: AnsiString;
U: String;
begin
    LoadStringFromFile(ExpandConstant('{app}\prefs.ini'), A);
    U := A;
    StringChange(U, '0000000000000000', Page.Values[0]);
    A := U;
    SaveStringToFile(ExpandConstant('{app}\prefs.ini'), A, False);
end;

procedure CurStepChanged(CurStep: TSetupStep);
Begin
if  CurStep=ssPostInstall then
  begin
    WriteUserInput;
  end
End;

Now what I need Inno to do is to leave the user input as it is, if it's already 16 digits, of fill with 0's at end, if it's less than 16 (e.g only one 0 if it's 15 digits, two if it's 14, etc.). What function would be able to do that?


Solution

  • A generic function for right-padding a string to a certain length with a given character:

    function PadStr(S: string; C: Char; I: Integer): string;
    begin
      Result := S + StringOfChar(C, I - Length(S));
    end;
    

    For your particular need, use:

    StringChange(U, '0000000000000000', PadStr(Page.Values[0], '0', 16));
    

    If you need the padding on compile-time (in the preprocessor), see How to pad version components with zeroes for OutputBaseFilename in Inno Setup.