How to move the first word to the end of a string in Pascal

1 Answer

0 votes
program MoveFirstWord;

function MoveFirstWordToEndOfString(s: string): string;
var
  firstWord, rest: string;
  i, startPos, endPos: integer;
begin
  { Skip leading spaces }
  i := 1;
  while (i <= Length(s)) and (s[i] = ' ') do
    Inc(i);
  startPos := i;

  { Find end of first word }
  while (i <= Length(s)) and (s[i] <> ' ') do
    Inc(i);
  endPos := i - 1;

  { Extract first word }
  firstWord := Copy(s, startPos, endPos - startPos + 1);

  { Extract the rest of the string }
  rest := Copy(s, endPos + 1, Length(s) - endPos);

  { Trim leading spaces from rest }
  while (Length(rest) > 0) and (rest[1] = ' ') do
    Delete(rest, 1, 1);

  { Build result }
  if rest = '' then
    MoveFirstWordToEndOfString := firstWord
  else
    MoveFirstWordToEndOfString := rest + ' ' + firstWord;
end;

var
  s: string;
begin
  s := 'Would you like to know more? (Explore and learn)';
  WriteLn(MoveFirstWordToEndOfString(s));
end.




(*
run:

you like to know more? (Explore and learn) Would

*)


 



answered Feb 5 by avibootz
...