How to remove text between parentheses in a string using C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void clean_string(const char *input, char *output) {
    int inside = 0;       // flag for parentheses
    int space_pending = 0; // flag for collapsing spaces
    int j = 0;

    for (int i = 0; input[i] != '\0'; i++) {
        char c = input[i];

        if (c == '(') {
            inside = 1;   // enter parentheses
        } else if (c == ')') {
            inside = 0;   // exit parentheses
        } else if (!inside) {
            if (isspace((unsigned char)c)) {
                space_pending = 1; // mark that we saw space
            } else {
                if (space_pending && j > 0) {
                    output[j++] = ' '; // collapse multiple spaces into one
                    space_pending = 0;
                }
                output[j++] = c; // copy non-space character
            }
        }
    }
    output[j] = '\0'; // null-terminate
}

int main() {
    char str[] = "Hello (remove this) from the future (and this too)";
    char result[100]; // ensure large enough buffer

    clean_string(str, result);

    printf("Original: %s\n", str);
    printf("Cleaned : %s\n", result);

    return 0;
}


/*
run:

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

*/

 



answered Dec 17, 2025 by avibootz
edited Dec 17, 2025 by avibootz

Related questions

...