#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
*/