program RemoveLastWordProgram;
uses
SysUtils, StrUtils;
function RemoveLastOccurrence(const s, wordToRemove: string): string;
var
posLast, searchPos, lenWord: Integer;
resultStr: string;
begin
resultStr := s;
lenWord := Length(wordToRemove);
posLast := 0;
searchPos := 1;
{ Find the last real substring occurrence }
while True do
begin
searchPos := PosEx(wordToRemove, resultStr, searchPos);
if searchPos = 0 then
Break;
posLast := searchPos;
Inc(searchPos);
end;
if posLast = 0 then
begin
RemoveLastOccurrence := resultStr; { word not found }
Exit;
end;
{ Remove the word }
Delete(resultStr, posLast, lenWord);
{ Remove double spaces created by deletion }
while Pos(' ', resultStr) > 0 do
resultStr := StringReplace(resultStr, ' ', ' ', []);
{ Trim leading/trailing spaces }
resultStr := Trim(resultStr);
RemoveLastOccurrence := resultStr;
end;
var
s: string;
begin
s := 'c++ c python c++ java c++ php';
s := RemoveLastOccurrence(s, 'c++');
Writeln(s);
end.
(*
run:
c++ c python c++ java php
*)