繁体   English   中英

在C中将字符串拆分为字符串数组

[英]Splitting a string into an array of strings in C

这个问题使我感到沮丧。 我之前已经解决了它,但我不记得确切了,它一次又一次地出现了!

系统会为您提供一个字符串,例如水果列表,并用逗号分隔。 您要在逗号处将字符串拆分为字符串数组。 我不知道为什么我会不断出现细分错误! 这是我的代码:

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

天哪,我脑袋大了……

答案很简单,我使用的字符串是具有只读访问权限的常量。 声明这样的字符串: 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM