I was wondering how you could take 1 string, split it into 2 with a delimiter, such as space, and assign the 2 parts to 2 separate strings. I've tried using strtok()
but to no avail.
split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.
The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.
#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);
Note that on some operating systems, strtok
man page mentions:
This interface is obsoleted by strsep(3).
An example with strsep
is shown below:
char* token; char* string; char* tofree; string = strdup("abc,def,ghi"); if (string != NULL) { tofree = string; while ((token = strsep(&string, ",")) != NULL) { printf("%s\n", token); } free(tofree); }
For purposes such as this, I tend to use strtok_r() instead of strtok().
For example ...
int main (void) { char str[128]; char *ptr; strcpy (str, "123456 789asdf"); strtok_r (str, " ", &ptr); printf ("'%s' '%s'\n", str, ptr); return 0; }
This will output ...
'123456' '789asdf'
If more delimiters are needed, then loop.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With