In short, currently the code below outputs: The substring is AES
. Unfortunately, I'm looking to get the result The substring is 100
. This is due to the fact that strsep()
keeps only the first portion of the split, and not the second. Is there a way to make the 2nd portion the one that's kept instead?
#include <stdio.h>
#include <string.h>
int main () {
const char haystack[50] = "SHA1 = 99\nAES = 100";
const char needle[10] = "Point";
char *ret;
char *bonus;
ret = strstr(haystack, "AES");
bonus = strsep(&ret, "=");
printf("The substring is: %s\n", bonus);
return(0);
}
From strsep
function's documentation :
char *strsep(char **stringp, const char *delim);
If
*stringp
is NULL, thestrsep()
function returnsNULL
and does nothing else. Otherwise, this function finds the first token in the string*stringp
, that is delimited by one of the bytes in the stringdelim
. This token is terminated by overwriting the delimiter with a null byte ('\0'
), and*stringp
is updated to point past the token. In case no delimiter was found, the token is taken to be the entire string*stringp
, and*stringp
is madeNULL
.
So in your program's case you should print ret
instead of bonus
:
bonus = strsep(&ret, "=");
printf("The substring is: %s\n", ret);
Since ret
will point past the token "="
.