How to get the indexes of words from an array of strings that start with a specific letter in Pascal

1 Answer

0 votes
program FindIndexes;

var
  words: array of string;
  i: Integer;
  specificLetter: Char;
  indexes: array of Integer;
  indexCount: Integer;

begin
  words := ['zero', 'one', 'two', 'three', 'four', 'five', 
            'six', 'seven', 'eight', 'nine', 'ten'];

  specificLetter := 't';

  // Initialize the indexes array
  SetLength(indexes, Length(words));
  indexCount := 0;

  // Iterate through the words array
  for i := 0 to High(words) do
  begin
    if (Length(words[i]) > 0) and (LowerCase(words[i][1]) = LowerCase(specificLetter)) then
    begin
      indexes[indexCount] := i;
      Inc(indexCount);
    end;
  end;

  // Resize the indexes array to the actual number of found indexes
  // To smaller size
  SetLength(indexes, indexCount);

  Write('Indexes of words starting with "', specificLetter, '": ');
  for i := 0 to High(indexes) do
  begin
    Write(indexes[i], ' ');
  end;
end.



(*
run:

Indexes of words starting with "t": 2 3 10 

*)

 



answered Mar 14, 2025 by avibootz
...