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

1 Answer

0 votes
#include <iostream>
#include <string>

/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
std::string removeParenthesesWithContent(const std::string& text) {
    std::string result;
    int depth = 0;  // Tracks whether we are inside parentheses

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

    // Trim extra spaces created after removal
    std::string cleaned;
    bool space = false;
    for (char c : result) {
        if (std::isspace(static_cast<unsigned char>(c))) {
            if (!space) cleaned += ' ';
            space = true;
        } else {
            cleaned += c;
            space = false;
        }
    }

    // Final trim of leading/trailing spaces
    if (!cleaned.empty() && cleaned.front() == ' ')
        cleaned.erase(cleaned.begin());
    if (!cleaned.empty() && cleaned.back() == ' ')
        cleaned.pop_back();

    return cleaned;
}

int main() {
    std::string str = "(An) API (API) (is a) (connection) connects (between) computer programs";
    std::string output = removeParenthesesWithContent(str);

    std::cout << output << std::endl;
}



/*
run:

API connects computer programs

*/

 



answered 3 hours ago by avibootz
edited 2 hours ago by avibootz
...