#include <stdio.h>
#include <string.h>
int main() {
char *slogan = "together{kaliya} [namak]";
char *slow_gun = strdup(slogan);
char *token = strsep(&slow_gun, "{");
printf ("\n slow_gun: %s\n token: %s\n", slow_gun, token);
return 0;
}
when I execute it:
$ cc -o try try_strsep.c
$ ./try
slow_gun: kaliya} [namak]
token: together
But when, I change the char *slogan to:
char *slogan = "kalia} [namak]";
and execute the same program:
$ vi try_strsep.c
$ cc -o try try_strsep.c
$ ./try
slow_gun: (null)
token: kalia} [namak]
My Question is, so when I use strsep() and input string does not have the pattern I am looking for, the return of strsep() is wrong. The only way I can validate whether strsep() could not find the pattern is to check if (slow_gun == NUll)
.
If I have char *slogan = "together{"
then strsep
would successfully return token
but returns slow_gun
to blank (not null
)
$ cc -o try try_strsep.c
$ ./try
slow_gun:
token: together
Is there a way I could avoid this IF check and rely on the function to return me the substr and if its not there, return NULL
?
free
the string returned bystrdup
– Chelyabinsk