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,950 questions

51,892 answers

573 users

How to remove the last n occurrences of a substring in a string in Pascal

1 Answer

0 votes
program RemoveLastNOccurrencesProgram;

function FindAllOccurrences(const s, sub: string; var posArr: array of Integer): Integer;
var
  i, j, k, count, lenS, lenSub: Integer;
  match: Boolean;
begin
  lenS := Length(s);
  lenSub := Length(sub);
  count := 0;

  i := 1;
  while i <= lenS - lenSub + 1 do
  begin
    match := True;
    for j := 1 to lenSub do
      if s[i + j - 1] <> sub[j] then
      begin
        match := False;
        Break;
      end;

    if match then
    begin
      posArr[count] := i;
      Inc(count);
    end;

    Inc(i);
  end;

  FindAllOccurrences := count;
end;

procedure RemoveAt(var s: string; pos, lenSub: Integer);
var
  i: Integer;
begin
  for i := pos to Length(s) - lenSub do
    s[i] := s[i + lenSub];
  SetLength(s, Length(s) - lenSub);
end;

procedure RemoveLastN(var s: string; sub: string; n: Integer);
var
  posArr: array[0..100] of Integer;
  count, i: Integer;
begin
  count := FindAllOccurrences(s, sub, posArr);

  for i := count - 1 downto 0 do
  begin
    if n = 0 then Break;
    RemoveAt(s, posArr[i], Length(sub));
    Dec(n);
  end;
end;

procedure RemoveExtraSpaces(var s: string);
var
  i, j: Integer;
begin
  i := 1;
  j := 1;

  { Skip leading spaces }
  while (i <= Length(s)) and (s[i] = ' ') do
    Inc(i);

  while i <= Length(s) do
  begin
    if (s[i] = ' ') and ((j = 1) or (s[j - 1] = ' ')) then
    begin
      Inc(i);
      Continue;
    end;

    s[j] := s[i];
    Inc(i);
    Inc(j);
  end;

  { Remove trailing space }
  if (j > 1) and (s[j - 1] = ' ') then
    Dec(j);

  SetLength(s, j - 1);
end;

var
  text: string;
begin
  text := 'abc xyz xyz abc xyzabcxyz abc';

  RemoveLastN(text, 'xyz', 3);
  Writeln(text);

  RemoveExtraSpaces(text);
  Writeln(text);
end.





(*
run:

abc xyz  abc abc abc
abc xyz abc abc abc

*)


 



answered 6 hours ago by avibootz
...