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
*)