How to remove text between parentheses in a string using Pascal

1 Answer

0 votes
program RemoveTextBetweenParentheses

function CleanString(s: string): string;
var
  i: Integer;
  inside: Integer;   { counter for parentheses nesting }
  spacePending: Boolean;
  resultStr: string;
begin
  inside := 0;
  spacePending := False;
  resultStr := '';

  for i := 1 to Length(s) do
  begin
    case s[i] of
      '(' : Inc(inside);   { enter parentheses }
      ')' : if inside > 0 then Dec(inside); { exit parentheses }
      ' ' : if inside = 0 then
              spacePending := True; { mark space }
    else
      if inside = 0 then
      begin
        if spacePending and (Length(resultStr) > 0) then
        begin
          resultStr := resultStr + ' ';
          spacePending := False;
        end;
        resultStr := resultStr + s[i];
      end;
    end;
  end;

  CleanString := resultStr;
end;

var
  original, cleaned: string;
begin
  original := 'Hello (remove this) from the future (and this too)';
  cleaned := CleanString(original);

  writeln('Original: ', original);
  writeln('Cleaned : ', cleaned);
end.




(*
run:

Original: Hello (remove this) from the future (and this too)
Cleaned : Hello from the future

*)

 



answered Dec 17, 2025 by avibootz
edited Dec 17, 2025 by avibootz

Related questions

...