What could be the simplest way to split strings in an array and put it to array of array of strings in C.
For example
["this is a test", "this is also a test"]
into
[["this", "is", "a", "test"], ["this", "is", "also", "a", "test"]]
What could be the simplest way to split strings in an array and put it to array of array of strings in C.
For example
["this is a test", "this is also a test"]
into
[["this", "is", "a", "test"], ["this", "is", "also", "a", "test"]]
Use strtok function from the C library. The function splits a string into a serie of tokens.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char **split(const char *s);
int main(void){
const char *org[] = {"this is a test", "this is also a test"};
char **explode[sizeof(org)/sizeof(*org)];
int i,j, n = sizeof(org)/sizeof(*org);
for(i=0;i < n; ++i){
char **p;
p = explode[i] = split(org[i]);
for(j=0;p[j];++j)//while(*p)
puts(p[j]); // puts(*p++)
printf("\n");
//free(explode[i][0]);//top is clone of original
//free(explode[i]);
}
return 0;
}
static int wordCount(const char *s){
char prev = ' ';
int wc = 0;
while(*s){
if(isspace(prev) && !isspace(*s)){
++wc;
}
prev = *s++;
}
return wc;
}
char **split(const char *s){
int i=0, wc = wordCount(s);
char *word, **result = calloc(wc+1, sizeof(char*));
char *clone = strdup(s);//Note that you are copying a whole
for(word=strtok(clone, " \t\n"); word; word=strtok(NULL, " \t\n")){
result[i++] = word;//or strdup(word); and free(clone); before return
}
return result;
}