gpt4 book ai didi

c - C中的分词器程序

转载 作者:太空宇宙 更新时间:2023-11-04 08:21:46 25 4
gpt4 key购买 nike

我刚开始学习如何用 C 编程,我被要求编写一个分词器程序,它将句子中的单词分成不同的分词,基本上就是 strtok() 的作用。

#include <stdio.h>
#include <stdlib.h>
int tokenise(char str[], int start, char result[]);
int main(){
const int MAX_STRING = 256;
char buffer[MAX_STRING];
int start;
int count;
int i;
char result[MAX_STRING];
fgets(buffer, MAX_STRING, stdin);
printf("%s\n", buffer);
start = tokenise(buffer, 0, result);
while(start != -1){
printf("%s\n", result);
start = tokenise(buffer, start, result);
}
int tokenise(char str[], int start, char result[])
{
int j;
for( i = start; str[i] != ' '; i++)
{
result[j] = str[i];
j++;
}
j = 0;
return -1;
}
}

这是我目前的代码,我不明白为什么我的函数不起作用。是我做错了什么基本的事情还是我犯了严重的错误?我也很困惑为什么我的讲师有

start = tokenise(buffer, 0 , result);

在 while 循环的正上方。感谢您提供任何帮助,谢谢。

最佳答案

  • 无论函数的结果如何,您总是返回 -1
  • 您不需要寻找换行符 '\n' 和其他此类空白字符。考虑在 ctype.h 中使用 isspace() 函数。
  • 您不寻找字符串的结尾,'\0',这意味着如果字符串中没有空格,您的程序将会崩溃。

关于c - C中的分词器程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33101401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com