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

2 Answers

0 votes
/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
public class Main {

    public static String removeParenthesesWithContent(String text) {
        StringBuilder result = new StringBuilder();
        int depth = 0;  // Tracks whether we are inside parentheses

        // Loop through each character
        for (char c : text.toCharArray()) {
            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
        StringBuilder cleaned = new StringBuilder();
        boolean space = false;

        for (char c : result.toString().toCharArray()) {
            if (Character.isWhitespace(c)) {
                if (!space) cleaned.append(' ');
                space = true;
            } else {
                cleaned.append(c);
                space = false;
            }
        }

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

    public static void main(String[] args) {
        String str = "(An) API (API) (is a) (connection) connects (between) computer programs";
        String output = removeParenthesesWithContent(str);

        System.out.println(output);
    }
}


/*
run:

API connects computer programs

*/

 



answered Jun 1 by avibootz
0 votes
/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
public class Main {

    public static String removeParenthesesWithContent(String text) {
        // Remove parentheses and everything inside them
        String cleaned = text.replaceAll("\\([^)]*\\)", " ");

        // Collapse multiple spaces into one (idiomatic Java)
        String collapsed = String.join(" ", cleaned.trim().split("\\s+"));

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

    public static void main(String[] args) {
        String str =
            "(An) API (API) (is a) (connection) connects (between) computer programs";

        String output = removeParenthesesWithContent(str);

        System.out.println(output);
    }
}


/*
run:

API connects computer programs

*/

 



answered Jun 1 by avibootz

Related questions

...