How to remove text between parentheses in a string using C++

1 Answer

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

std::string remove_parentheses_and_spaces(const std::string& input) {
    std::string temp;
    bool inside = false;

    // Step 1: Remove text inside parentheses
    for (char c : input) {
        if (c == '(') {
            inside = true;
        } else if (c == ')') {
            inside = false;
        } else if (!inside) {
            temp.push_back(c);
        }
    }

    // Step 2: Normalize spaces (collapse multiple spaces into one)
    std::istringstream iss(temp);
    std::string word, output;
    while (iss >> word) {                 // operator>> skips extra spaces
        if (!output.empty()) output += " ";
        output += word;
    }

    return output;
}

int main() {
    std::string text = "Hello (remove this) from the future (and this too)";
    
    std::cout << "Original: " << text << "\n";
    std::cout << "Cleaned : " << remove_parentheses_and_spaces(text) << "\n";
}



/*
run:

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

*/

 



answered Dec 17, 2025 by avibootz

Related questions

...