在定界符处分割字符串并将子字符串存储在C中的char ** array中 [英] Splitting a string at a delimiter and storing substrings in char **array in C

查看:76
本文介绍了在定界符处分割字符串并将子字符串存储在C中的char ** array中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,该函数将用户在命令行上给定的字符串按第一次出现的逗号分隔并放入数组中。

I want to write a function that splits a string given by the user on the command-line by the first occurrence of a comma and put in an array.

这是我尝试做的事情:

char**split_comma(const str *s) {
    char *s_copy = s;

    char *comma = strchr(s_copy, ",");

    char **array[2];
    *(array[0]) = strtok(s_copy, comma);
    *(array[1]) = strtok(NULL,comma);
return array;
}

这是主要功能:

int main(int argc, char **argv) {
   char **r = split_comma(argv[1]);
   printf("substring 1: %s, substring 2: %s\n", r[0],r[1]);
   return 0;
}

有人能给我一些为什么不能奏效的见解吗?

Can someone please give me some insight as to why this doesn't work?

推荐答案

这有效。

char **split_on_comma(const char *s) {
    char ** result;
    result = malloc(sizeof(char*)*2);
    result[0] = malloc(sizeof(char) *200);
    result[1] = malloc(sizeof(char) *200);
    char *position;
    position = strchr(s, ',');
    strcpy(result[1], position +1);
    strncpy(result[0], s, position -s);
    return result;
}

这篇关于在定界符处分割字符串并将子字符串存储在C中的char ** array中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆