Your code will not work because strtok
does not work the way you think it does. When called the first time like this:
char *p = strtok(data,"(");
It will:
- skip until the first char that's not a delimiter.
- then try to find the next delimiter.
- replace the last delimiter with a
\0
.
- return a pointer to the first char of the token.
Since step two fails (there are no more delimiters) strtok will simply return NULL
indicating that it didn't find any tokens. Any further calls to strtok
for the same input will also return NULL
.
You can change this by adding the ending delimiter in the first call like this:
char *p = strtok(data,"()");
Now strtok
will find a token, and return a pointer to the first x
in your example. Notice though, that since it only replaced the terminating delimiter with a \0
, the opening parentesis is still present in data
.
To get rid of that one you could do something like this:
char *p = strtok(data,"()");
strcpy(data, p);
However I would rather recommend building a new string for the results if you have any other content in the source data as well.