How to remove the middle word from a string in Pascal

1 Answer

0 votes
program RemoveMiddleWord;

const
  MaxWords = 50;

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

procedure SplitWords(s: string; var words: TStringArray; var count: integer);
var
  i: integer;
  current: string;
begin
  count := 0;
  current := '';

  for i := 1 to Length(s) do
  begin
    if s[i] = ' ' then
    begin
      if current <> '' then
      begin
        Inc(count);
        words[count] := current;
        current := '';
      end;
    end
    else
      current := current + s[i];
  end;

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

function RemoveMiddleWord(const s: string): string;
var
  words: TStringArray;
  count, mid, i: integer;
  resultStr: string;
begin
  SplitWords(s, words, count);

  if count <= 2 then
  begin
    RemoveMiddleWord := s;
    Exit;
  end;

  { FIX: Pascal arrays are 1-based }
  mid := (count div 2) + 1;

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

  RemoveMiddleWord := resultStr;
end;

var
  str, resultStr: string;

begin
  str := 'c pascal c++ java rust';
  
  resultStr := RemoveMiddleWord(str);
  
  WriteLn(resultStr);
end.




(*
run:

c pascal java rust

*)


 



answered Dec 24, 2025 by avibootz
...