Curnelious Curnelious - 1 year ago 93
C Question

Removing characters from original string?

This may be basic, please be patient with me,

char data[]="(xxx)";

I would like to remove the () and leave data only to be

char *p = strtok(data,"(");
p = strtok(NULL,")");
printf("this data: %s \n",p);
printf("this data: %s \n",data);

  1. p should be xxx but its NULL , data stay the same (strtok should affect the source?)

  2. this will not change data, I would like a way to manipulate data to be

a3f a3f
Answer Source
char *in_parens(char* str) {
   char *end, *start;
   if (!(end = strrchr(str, ')'))) return NULL;
   if (!(start = strchr(str, '('))) return NULL;
   *end = '\0';
   return start + 1;

int main(void) {
    char data[] = "a(x(b)x)c";
    printf("%s\n", in_parens(data)); // prints x(b)x

Returns NULL if string doesn't contain a () pair. Otherwise, strips outermost pair and returns what's inside.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download