C将字符串拆分为int数组

时间:2014-11-25 04:32:07

标签: c

我的char*格式为:

* SEARCH 1 2 3 ...

具有由空格分隔的可变数量的整数。我想编写一个函数来返回int[]之后带有整数的* SEARCH

我该如何写这个函数?

1 个答案:

答案 0 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *f(const char *s, int *n /* out */){
    if(strncmp(s, "* SEARCH", 8)!=0){
        fprintf(stderr, "format error!\n");
        *n = 0;
        return NULL;
    }
    s += 8;
    const char *p = s;
    int v, len, status;
    int count = 0;
    while((status=sscanf(p, "%d%n", &v, &len))==1){
        ++count;
        p +=len;
    }
    if(status==0){
        fprintf(stderr, "format error!\n");
        *n = 0;
        return NULL;
    }
    int *ret = malloc(count * sizeof(*ret));
    p = s;
    count = 0;
    while(EOF!=sscanf(p, "%d%n", &v, &len)){
        ret[count++]=v;
        p +=len;
    }
    *n = count;
    return ret;
}

int main (void){
    int i, n, *nums = f("* SEARCH 1 2 3", &n);

    for(i=0; i<n; ++i)
        printf("%d ", nums[i]);
    printf("\n");
    free(nums);
    return 0;
}