Why is strtok changing its input like this?

When strtok() finds a token, it changes the character immediately after the token into a \0, and then returns a pointer to the token. The next time you call it with a NULL argument, it starts looking after the separators that terminated the first token — i.e., after the \0, and possibly further along. Now, … Read more

How to split a string to 2 strings in C

#include <string.h> char *token; char line[] = “SEVERAL WORDS”; char *search = ” “; // Token will point to “SEVERAL”. token = strtok(line, search); // Token will point to “WORDS”. token = strtok(NULL, search); Update Note that on some operating systems, strtok man page mentions: This interface is obsoleted by strsep(3). An example with strsep … Read more

C: correct usage of strtok_r

The documentation for strtok_r is quite clear. The strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string. On the first call to strtok_r(), str should point to … Read more

Split string into tokens and save them in an array

#include <stdio.h> #include <string.h> int main () { char buf[] =”abc/qwe/ccd”; int i = 0; char *p = strtok (buf, “https://stackoverflow.com/”); char *array[3]; while (p != NULL) { array[i++] = p; p = strtok (NULL, “https://stackoverflow.com/”); } for (i = 0; i < 3; ++i) printf(“%s\n”, array[i]); return 0; }

strtok segmentation fault

The problem is that you’re attempting to modify a string literal. Doing so causes your program’s behavior to be undefined. Saying that you’re not allowed to modify a string literal is an oversimplification. Saying that string literals are const is incorrect; they’re not. WARNING : Digression follows. The string literal “this is a test” is … Read more

Using strtok() in nested loops in C?

Yes, strtok(), indeed, uses some static memory to save its context between invocations. Use a reentrant version of strtok(), strtok_r() instead, or strtok_s() if you are using VS (identical to strtok_r()). It has an additional context argument, and you can use different contexts in different loops. char *tok, *saved; for (tok = strtok_r(str, “%”, &saved); … Read more

Using strtok in c

Here is my take at a reasonably simple tokenize helper that stores results in a dynamically growing array null-terminating the array keeps the input string safe (strtok modifies the input string, which is undefined behaviour on a literal char[], at least I think in C99) To make the code re-entrant, use the non-standard strtok_r #include … Read more