How to remove parentheses and the text inside them from a string in Pascal

1 Answer

0 votes
program RemoveParentheses;

{$mode objfpc}{$H+}

uses
  SysUtils;

(**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 *)
function removeParenthesesWithContent(const text: string): string;
var
  resultStr: string;
  cleaned: string;
  depth: Integer;  // Tracks whether we are inside parentheses
  i: Integer;
  c: Char;
  space: Boolean;
begin
  resultStr := '';
  depth := 0;

  // Loop through each character
  for i := 1 to Length(text) do
  begin
    c := text[i];

    if c = '(' then
    begin
      depth := depth + 1;        // Enter parentheses
      Continue;
    end;

    if c = ')' then
    begin
      if depth > 0 then
        depth := depth - 1;      // Exit parentheses
      Continue;
    end;

    if depth = 0 then
      resultStr := resultStr + c;   // Only copy characters outside parentheses
  end;

  // Trim extra spaces created after removal
  cleaned := '';
  space := False;

  for i := 1 to Length(resultStr) do
  begin
    c := resultStr[i];

    if c <= ' ' then
    begin
      if not space then
        cleaned := cleaned + ' ';
      space := True;
    end
    else
    begin
      cleaned := cleaned + c;
      space := False;
    end;
  end;

  // Final trim of leading/trailing spaces
  cleaned := Trim(cleaned);

  Result := cleaned;
end;

var
  str: string;
  output: string;

begin
  str := '(An) API (API) (is a) (connection) connects (between) computer programs';
  output := removeParenthesesWithContent(str);

  WriteLn(output);

end.



(*
run:

API connects computer programs

*)

 



answered 1 day ago by avibootz

Related questions

...