Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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

1 Answer

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

/* Remove parentheses and the text inside them.
 * Writes the cleaned result into out[].
 * Assumes out[] is large enough.
 */
void removeParenthesesWithContent(const char *in, char *out) {
    int depth = 0;   /* >0 means we are inside parentheses */
    int j = 0;

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

        if (c == '(') {
            depth++;
            continue;
        }
        if (c == ')') {
            if (depth > 0) depth--;
            continue;
        }
        if (depth == 0) {
            out[j++] = c;
        }
    }

    out[j] = '\0';
}

/* Trim extra spaces in-place */
void trimSpaces(char *s) {
    int i = 0, j = 0;
    int space = 0;

    /* Skip leading spaces */
    while (isspace((unsigned char)s[i])) {
        i++;
    }

    while (s[i] != '\0') {
        if (isspace((unsigned char)s[i])) {
            if (!space) s[j++] = ' ';
            space = 1;
        } else {
            s[j++] = s[i];
            space = 0;
        }
        i++;
    }

    /* Remove trailing space */
    if (j > 0 && s[j-1] == ' ')
        j--;

    s[j] = '\0';
}

int main(void) {
    const char *str =
        "(An) API (API) (is a) (connection) connects (between) computer programs";

    char cleaned[256];

    removeParenthesesWithContent(str, cleaned);
    trimSpaces(cleaned);

    printf("%s\n", cleaned);

    return 0;
}



/*
run:

API connects computer programs

*/

 



answered Jun 1 by avibootz

Related questions

...