Reputation: 6755
Is there a way in C to split a string (using strtok
or any other way) where the delimiter is more than one character in length? I'm looking for something like this:
char a[14] = "Hello,World!";
char *b[2];
b[0] = strtok(a, ", ");
b[1] = strtok(NULL, ", ");
I want this to not split the string because there is no space between the comma and the W. Is there a way to do that?
Upvotes: 12
Views: 8071
Reputation: 37447
You can use char * strstr(const char *haystack, const char *needle)
to locate your delimiter string within your string.
char a[14] = "Hello,World!";
char b[2] = ", ";
char *start = a;
char *delim;
do {
delim = strstr(start, b);
// string between start and delim (or end of string if delim is NULL).
start = delim + 2; // Use lengthof your b string.
} while (delim);
Upvotes: 4
Reputation: 6593
Something like this maybe? No guarantees that this compiles. ;)
char* strstrtok(char *haystack, char *needle) {
static char *remaining = null;
char *working;
if(haystack)
working = haystack;
else if(remaining)
working = remaining;
else
return NULL;
char *result = working;
if(result = strstr(working, needle))
remaining = working + strlen(needle) + 1;
return result;
}
Upvotes: 1