最简单的方法是在数组中拆分字符串并将其放入C中的字符串数组数组中

时间:2014-09-28 11:36:05

标签: c arrays string

在数组中拆分字符串并将其放入C中字符串数组的最简单方法是什么。

例如

["this is a test", "this is also a test"]

进入

[["this", "is", "a", "test"], ["this", "is", "also", "a", "test"]]

2 个答案:

答案 0 :(得分:2)

使用C库中的strtok函数。该函数将字符串拆分为一系列标记。

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

答案 1 :(得分: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;
}