How to reverse each word in a string with Pascal

1 Answer

0 votes
program ReverseEachWord;

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

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

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

// Function to reverse a single word
function ReverseWord(s: string): string;
var
  i: Integer;
  r: string;
begin
  r := '';
  for i := Length(s) downto 1 do
    r := r + s[i];
  ReverseWord := r;
end;

// Function to reverse each word in the array and join them
function ReverseEachWordInAString(Words: TStringArray; Count: Integer): string;
var
  i: Integer;
  ResultStr: string;
begin
  ResultStr := '';
  for i := 1 to Count do
  begin
    ResultStr := ResultStr + ReverseWord(Words[i]);
    if i < Count then
      ResultStr := ResultStr + ' ';
  end;
  ReverseEachWordInAString := 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;

  // Reverse each word and join
  OutputStr := ReverseEachWordInAString(Words, WordCount);

  WriteLn(OutputStr);
end.



(*
run:

avaj ++c tsur nohtyp #c lacsap

*)


 



answered Sep 24, 2025 by avibootz
...