【问题标题】:Splitting a string into an array of strings in C在C中将字符串拆分为字符串数组
【发布时间】:2014-12-15 20:51:11
【问题描述】:

这个问题让我很沮丧;我以前解决过它,但我不记得到底是怎么解决的了,而且一次又一次地出现!

给你一个字符串,就像一个水果列表,用逗号分隔。您想将字符串拆分为逗号处的字符串数组。我不知道为什么我不断收到分段错误!这是我的代码:

char** split(char *);
int count_words(char *);

int main(int argc, char **argv) {

  char *my_list = "Apple, banana, cherry, dragonfruit, elderberry";
  char **split_list = split(my_list);

  /*int i = 0;
  while(split_list[i] != NULL) {
    printf("%s\n", split_list[i]);
    i++;
    }*/

  return 0;
}

char** split(char *str) {
  int num_words = count_words(str);
  char **my_words = malloc((num_words + 1) * sizeof(char*));

  const char delim[2] = ",";
  char *token;
  token = strtok(str, delim);

  for(int i = 0; i < num_words; i++) {
    my_words[i] = malloc(sizeof(char) * strlen(token));
    strcpy(my_words[i], token);

    token = strtok(NULL, delim);
  }

  my_words[i] = NULL;

  return my_words;
}

int count_words(char *str) {
  int cnt = 0;
  while(*str != '\0') {
    if(*str == ',') cnt++;
    str++;
  }

  return ++cnt;
}

【问题讨论】:

  • token开始抄袭不是晚了一个字吗?它将指向右侧第一个逗号之后。
  • my_words[i] = NULL; - 这可以编译吗?如果是这样,此时 i 的值是多少?
  • 您正在尝试拆分只读字符串文字。
  • 分割只读字符串是不行的。
  • 一个建议,更仔细地格式化你的代码,你将来会很开心。 :)

标签: c string split segmentation-fault


【解决方案1】:

我的天啊,我的脑洞太大了……

答案很简单,我使用的字符串是一个具有只读访问权限的常量。 像这样声明一个字符串:char *myStr = "Hello World" 是只读的!你不能写进去。

解决方案代码:

char** split(char *);
int count_words(char *);

int main(int argc, char **argv) {

    const char *string = "Apple, banana, cherry, dragonfruit, elderberry";
char *my_list = malloc(1 + strlen(string)); //random number
strcpy(my_list, string);
char **split_list = split(my_list);

int i = 0;
while(split_list[i] != NULL) {
    printf("%s\n", split_list[i]);
    free(split_list[i]);
    i++;
}
free(split_list);
free(my_list);

return 0;
}

char** split(char *str) {
int num_words = count_words(str);
char **my_words = malloc((1 + num_words) * sizeof(char*));
const char delim[2] = ",";
char *token;
token = strtok(str, delim);

int i = 0;
while(token != NULL) {
    my_words[i] = malloc(sizeof(char) * (1 + strlen(token)));
    strcpy(my_words[i], token);

    token = strtok(NULL, delim);
    i++;
}
my_words[i] = NULL;

return my_words;
}

int count_words(char *str) {
int cnt = 0;

while(*str != '\0')
{
    if(*str == ',')
        cnt++;
    str++;
}

return ++cnt;
}

【讨论】:

  • 所有 malloc 调用都有内存泄漏,您没有为 my_words[i] = malloc(sizeof(char) * strlen(token)); 中的空终止字节分配空间。而且您最初的字符串副本不是最好的主意。但是您的分析器仍然正确。
  • 是的,我可能太早发布了这个问题;我刚刚意识到我可以做到: char my_list[] = "Apple, Banana...etc";
猜你喜欢
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 2022-01-18
  • 2020-02-12
  • 2012-02-22
相关资源
最近更新 更多