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

1 Answer

0 votes
program MoveWordToEnd;

const
  MaxWords = 124;

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

procedure SplitWords(s: string; var words: TStringArray; var count: integer);
var
  p: integer;
  w: string;
begin
  count := 0;
  while s <> '' do
  begin
    p := Pos(' ', s);
    if p = 0 then
    begin
      w := s;
      s := '';
    end
    else
    begin
      w := Copy(s, 1, p - 1);
      Delete(s, 1, p);
    end;

    if w <> '' then
    begin
      Inc(count);
      words[count] := w;
    end;
  end;
end;

function MoveWordToEnd(const s, word: string): string;
var
  words: TStringArray;
  count, i, posWord: integer;
  resultStr: string;
begin
  SplitWords(s, words, count);

  { Find the word }
  posWord := 0;
  for i := 1 to count do
    if words[i] = word then
    begin
      posWord := i;
      break;
    end;

  { If found, remove and append }
  if posWord > 0 then
  begin
    for i := posWord to count - 1 do
      words[i] := words[i + 1];
    words[count] := word;
  end;

  { Rebuild string }
  resultStr := '';
  for i := 1 to count do
  begin
    if resultStr <> '' then
      resultStr := resultStr + ' ';
    resultStr := resultStr + words[i];
  end;

  MoveWordToEnd := resultStr;
end;

var
  s, word, resultStr: string;

begin
  s := 'Would you like to know more? (Explore and learn)';
  word := 'like';

  resultStr := MoveWordToEnd(s, word);
  writeln(resultStr);
end.





(*
run:

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

*)


 



answered Feb 3 by avibootz
...