How to reverse the order of the words in a string with Pascal

2 Answers

0 votes
program ReverseWords;

const
  InputStr = 'python java c c++ pascal';
  MaxWords = 10;

var
  Words: array[1..MaxWords] of string;
  WordCount, i: Integer;
  TempStr, OutputStr: string;

begin
  // Split the input string into words 
  TempStr := InputStr;
  WordCount := 0;

  while Length(TempStr) > 0 do
  begin
    Inc(WordCount);
    Words[WordCount] := Copy(TempStr, 1, Pos(' ', TempStr) - 1);
    Delete(TempStr, 1, Pos(' ', TempStr));
    if Pos(' ', TempStr) = 0 then
    begin
      Inc(WordCount);
      Words[WordCount] := TempStr;
      Break;
    end;
  end;

  // Reverse the words and join them into a single string 
  OutputStr := '';
  for i := WordCount downto 1 do
  begin
    OutputStr := OutputStr + Words[i];
    if i > 1 then
      OutputStr := OutputStr + ' ';
  end;

  WriteLn(OutputStr);
end.



(*
run:

pascal c++ c java python

*)

 



answered Sep 24, 2025 by avibootz
0 votes
program ReverseWords;

const
  InputStr = 'python java c c++ pascal';
  MaxWords = 10;

type
  TStringArray = array[1..MaxWords] of string;

var
  Words: TStringArray;
  WordCount: Integer;
  OutputStr: string;

// Function to reverse and join words into a single string
function ReverseAndJoin(Words: TStringArray; Count: Integer): string;
var
  i: Integer;
  ResultStr: string;
begin
  ResultStr := '';
  for i := Count downto 1 do
  begin
    ResultStr := ResultStr + Words[i];
    if i > 1 then
      ResultStr := ResultStr + ' ';
  end;
  ReverseAndJoin := ResultStr;
end;

var
  TempStr: string;
  SpacePos: Integer;

begin
  // Split the input string into words
  TempStr := InputStr;
  WordCount := 0;

  while Length(TempStr) > 0 do
  begin
    SpacePos := Pos(' ', TempStr);
    if SpacePos > 0 then
    begin
      Inc(WordCount);
      Words[WordCount] := Copy(TempStr, 1, SpacePos - 1);
      Delete(TempStr, 1, SpacePos);
    end
    else
    begin
      Inc(WordCount);
      Words[WordCount] := TempStr;
      TempStr := '';
    end;
  end;

  // Use the function to reverse and join
  OutputStr := ReverseAndJoin(Words, WordCount);

  WriteLn(OutputStr);
end.



(*
run:

pascal c++ c java python

*)


 



answered Sep 24, 2025 by avibootz
...