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

2 Answers

0 votes
using System;
using System.Text;

/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
class Program
{
    public static string RemoveParenthesesWithContent(string text)
    {
        var result = new StringBuilder();
        int depth = 0;  // Tracks whether we are inside parentheses

        // Loop through each character
        foreach (char c in text) {
            if (c == '(') {
                depth++;        // Enter parentheses
                continue;
            }
            if (c == ')') {
                if (depth > 0) depth--;  // Exit parentheses
                continue;
            }
            if (depth == 0) {
                result.Append(c);   // Only copy characters outside parentheses
            }
        }

        // Trim extra spaces created after removal
        var cleaned = new StringBuilder();
        bool space = false;

        foreach (char c in result.ToString()) {
            if (char.IsWhiteSpace(c)) {
                if (!space) cleaned.Append(' ');
                space = true;
            }
            else {
                cleaned.Append(c);
                space = false;
            }
        }

        // Final trim of leading/trailing spaces
        return cleaned.ToString().Trim();
    }

    static void Main()
    {
        string str = "(An) API (API) (is a) (connection) connects (between) computer programs";
        string output = RemoveParenthesesWithContent(str);

        Console.WriteLine(output);
    }
}



/*
run:

API connects computer programs

*/

 



answered Jun 1 by avibootz
0 votes
using System;
using System.Text.RegularExpressions;

/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
class Program
{
    public static string RemoveParenthesesWithContent(string text) {
        // Remove parentheses and everything inside them
        string cleaned = Regex.Replace(text, "\\([^)]*\\)", " ");

        // Collapse multiple spaces into one 
        string collapsed = string.Join(" ",
            cleaned.Trim().Split((char[])null, StringSplitOptions.RemoveEmptyEntries));

        // Final trim of leading/trailing spaces
        return collapsed.Trim();
    }

    static void Main()
    {
        string str =
            "(An) API (API) (is a) (connection) connects (between) computer programs";

        string output = RemoveParenthesesWithContent(str);

        Console.WriteLine(output);
    }
}


/*
run:

API connects computer programs

*/

 



answered Jun 1 by avibootz

Related questions

...