Hello. I am wondering how to split a string lets say char *a="raining apples training away" using a delimiter like "g a" and the result will be: rainin pples trainin way I tried using strstr but I got stuck. Any hints will be greatly appreciated. Thank you in advance!
Assuming you want to use the whole string "g a" as a delimiter rather than any of the characters in that string, the output would be:
rainin
pples trainin
way
It's certainly possible to do this with strstr(), but you need to be careful of two things:Make sure to skip over the delimiter before testing again
Make sure to account for the last token as strstr() will return NULL when there's one more left
Here's an example:
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *src = "raining apples training away";
const char *next = src;
while ((next = strstr(src, "g a")) != NULL) {
while (src != next)
putchar(*src++);
putchar('\n');
/* Skip the delimiter */
src += 3;
}
/* Handle the last token */
while (*src != '\0')
putchar(*src++);
putchar('\n');
return 0;
} Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401