如何用strtok在c中的字符数组中划分单词



我有一个名为"借口"的结构,它有字符,我需要存储至少20个借口。然后,我需要把每个借口的每个单词分成一个数组。

?我该怎么做?

#define excuseLength 256
typedef struct{
char sentence[excuseLength];
}excuse;
excuse listExcuses[20];
for (int listExcuses_i = 0; listExcuses_i < 20; listExcuses_i++)
{
char *input;
scanf("%s", input);
strcpy(listExcuses[listExcuses_i].sentence, input);
char* token = strtok(input, " ");
while(token != NULL){
printf("token: %sn", token);
token = strtok(NULL, " ");
}
}

以下是您可以添加到解决方案中的一些内容:

  • 检查fgets()的返回值,因为它在出错时返回NULL
  • 如果您决定仍使用scanf(),请确保使用scanf("%255s", input)代替char input[256]。使用格式说明符%255s而不是简单的%s来检查是否有过多的输入。总的来说,使用fgets()读取输入更好
  • 删除fgets()后面的'n'字符。这也有助于检查在input中输入的字符数是否超过256的限制,以及句子后面是否没有换行符。如果不删除此换行符,则strtok()分隔符必须为" n"
  • 代码中的#define常量,并将const char*用于字符串文字,例如strtok()的分隔符
  • 您还可以添加一些代码来检查来自fgets()的空输入。您可以简单地使用一个单独的计数器,并且只对找到的有效字符串递增该计数器
  • struct只有一个成员也很奇怪,通常结构包含多个成员。您可以简单地绕过使用结构,使用声明为char listexcuses[NUMEXCUSES][EXCUSELENGTH]的2D字符数组。此数组最多可容纳20个字符串,每个字符串的最大长度为256

以下是您的方法的一些修改代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EXCUSELENGTH 256
#define NUMEXCUSES 20
typedef struct {
char sentence[EXCUSELENGTH];
} excuse;
int main(void) {
excuse listexcuses[NUMEXCUSES];
char input[EXCUSELENGTH] = {''};
char *word = NULL;
const char *delim = " ";
size_t slen, count = 0;
for (size_t i = 0; i < NUMEXCUSES; i++) {
printf("nEnter excuse number %zu:n", count+1);
if (fgets(input, EXCUSELENGTH, stdin) == NULL) {
fprintf(stderr, "Error from fgets(), cannot read linen");
exit(EXIT_FAILURE);
}
slen = strlen(input);
if (slen > 0 && input[slen-1] == 'n') {
input[slen-1] = '';
} else {
fprintf(stderr, "Too many characters entered in excuse %zun", count+1);
exit(EXIT_FAILURE);
}
if (*input) {
strcpy(listexcuses[count].sentence, input);
count++;
printf("nTokens found:n");
word = strtok(input, delim);
while (word != NULL) {
printf("%sn", word);
word = strtok(NULL, delim);
}  
}
}
return 0;
} 

由于您最终需要将这些令牌存储在某个地方,因此您将需要另一种形式的存储这些数据。由于您不知道可以获得多少个令牌,也不知道每个令牌有多长,因此可能需要使用类似char**tokens的东西。这不是一个数组,但它是一个指向指针的指针。使用它将允许存储任意数量的单词和每个单词的任意长度。为此,您需要动态内存分配。这篇文章的答案会有所帮助。

我更改了fgets的扫描函数并初始化了char输入[256],现在它就可以工作了!

#define excuseLength 256
#define numberExcuses 20
typedef struct{
char sentence[excuseLength];
}excuse;
excuse listExcuses[20];
for (int listExcuses_i = 0; listExcuses_i < numberExcuses; listExcuses_i++)
{
char input[256];
scanf("%s", input);
fgets(input, 256, stdin);
strcpy(listExcuses[listExcuses_i].sentence, input);
char* token = strtok(input, " ");
while(token != NULL){
printf("token: %sn", token);
token = strtok(NULL, " ");
}
}

最新更新