0

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"]]
1
  • Opinion-based. List the methods you know. Commented Sep 28, 2014 at 11:41

2 Answers 2

2

Use strtok function from the C library. The function splits a string into a serie of tokens.

http://man7.org/linux/man-pages/man3/strtok.3.html

Sign up to request clarification or add additional context in comments.

Comments

1
#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;
}

1 Comment

May almighty God bless you, the Father, and the Son, and the Holy Spirit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.