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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,239 questions

56,142 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 Feb 15 by avibootz

Related questions

...