Guess what the output of this code is... there's no tricks, it's just a constant array and a "find the index" function.

Guess what the output of this code is... there's no tricks, it's just a constant array and a "find the index" function.

program console_test;

{$APPTYPE CONSOLE}

uses
  SysUtils;

const
  TEST_ARRAY: array[100..102] of string = ('one', 'two', 'three');

function IndexOfStringInArray(const AString: string; 
  aArray: array of string): Integer;
begin
  // SameText is case insensitive
  result := Low(aArray);
  while (result <= High(aArray)) 
    and not SameText(AString, aArray[result]) do
  begin
    Inc(result);
  end;
  if result > High(aArray) then
    raise Exception.Create('string not found in array');
end;

var
  i: Integer;
begin
  try
    WriteLn('String "one" found at index ',
      IndexOfStringInArray('one', TEST_ARRAY));
    //for i := Low(TEST_ARRAY) to High(TEST_ARRAY) do
    //  WriteLn(i, ' = ', TEST_ARRAY[i]);
    ReadLn;
  except
    on E: Exception do
      WriteLn(E.ClassName, ': ', E.Message);
  end;
end.

Comments

  1. If I remember correctly:
    Low(aArray)=0
    So it will return 0 even though I would expect 100.

    ReplyDelete
  2. Yup. Kind of annoying, but once you know it's just ugly.

    ReplyDelete

Post a Comment