Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,948 questions

51,890 answers

573 users

How to remove the last occurrence of a word from a string in Pascal

1 Answer

0 votes
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

*)


 



answered 4 hours ago by avibootz
...