How to split a string into an tokens and then save them in an array?
Specifically, I have a string "abc/qwe/jkh"
. I want to separate "/"
, and then save the tokens into an array.
Output will be such that
array[0] = "abc" array[1] = "qwe" array[2] = "jkh"
please help me
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
To split a string we need delimiters - delimiters are characters which will be used to split the string. Suppose, we've the following string and we want to extract the individual words. char str[] = "strtok needs to be called several times to split a string"; The words are separated by space.
You can represent a space (one or more) as a simple regular expression "\s+" and use a regex token iterator to iterate through the tokens, you can store the tokens in a vector from there.. Here is an example that just prints out the tokens. Using regular expressions for a simple substring search is an outright crime.
#include <stdio.h> #include <string.h> int main () { char buf[] ="abc/qwe/ccd"; int i = 0; char *p = strtok (buf, "/"); char *array[3]; while (p != NULL) { array[i++] = p; p = strtok (NULL, "/"); } for (i = 0; i < 3; ++i) printf("%s\n", array[i]); return 0; }
You can use strtok()
char string[] = "abc/qwe/jkh"; char *array[10]; int i = 0; array[i] = strtok(string, "/"); while(array[i] != NULL) array[++i] = strtok(NULL, "/");
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