如何使用我的自定义函数 split() 将一个句子拆分成单个单词?

How do I split a sentence into individual words using my custom function split()?

我正在尝试将用户的输入拆分为单独的词,然后在换行符上打印每个词。

我有一个函数 split(),它尝试使用 strtok() 方法来拆分每个单词。当我尝试循环遍历 Main() 中的单词以打印它们时,它根本就没有。

编译后出现两个错误

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

#define MAX 10
#define SIZE 256

char *read_line(char *buf, size_t sz) {
  printf("> ");
  fgets(buf, sz, stdin);
  buf[strcspn(buf, "\n")] = 0;
  return buf;
}

void split(char *buf, char *words[], size_t max) {
  char *temp = strtok(buf, " ");

  for (int i = 0; words[0] != '[=10=]'; i++) {
    strcpy(words[i], temp);
    temp = strtok(NULL, buf);
  }
}

int main(int argc, char **argv) {
  char *buf = malloc(SIZE);
  char *words = malloc(MAX * sizeof(char));

  while(1) {
    char *input = read_line(buf, SIZE);
    split(input, words, MAX);

    for (int i = 0; words[i] != '[=10=]'; i++) {
      printf("%s\n", words[i]);
    }
  }
}

有没有我正在做的或没有正确理解的事情?

有很多问题:

这就是你想要的。评论解释出了什么问题:

void split(char* buf, char* words[], size_t max) {
  char* temp = strtok(buf, " ");

  int i = 0;
  while (temp != NULL)            // wrong usage of strtok
  {
    words[i++] = strdup(temp);    // words[i] points nowhere, you need to allocate memory
    temp = strtok(NULL, " ");     // wrong usage of strtok
  }
  words[i] = NULL;                // you didn't terminate the words array
}

int main(int argc, char** argv) {
  char* buf = malloc(SIZE);        // this could be "char buf[SIZE];". It's not wrong
                                   // but there's no need for dynamically allocating memory here

  char** words = malloc(MAX * sizeof(char*));   // you need to allocate pointers to char, not char

  while (1) {
    char* input = read_line(buf, SIZE);
    split(input, words, MAX);

    for (int i = 0; words[i] != NULL; i++) {    // you need to check for the NULL pointer
      printf("%s\n", words[i]);                 // not the NUL char
    }
  }
}

还有进步空间,

  • split 函数不检查 max
  • 在程序结束时分配的内存没有正确释放
  • 为简洁起见,没有任何错误检查

strdup可能在你的平台上不可用,所以你可能需要自己实现它(基本上3行代码)