C中的分词器程序
Tokenizer programme in C
我刚开始学习如何用 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 循环的正上方。
感谢任何帮助,谢谢。
- 无论函数的结果如何,你总是return
-1
。
- 您不需要寻找换行符
'\n'
和其他类似的白色 space 字符。考虑在 ctype.h. 中使用 isspace()
函数
- 你不寻找字符串的结尾,
'[=13=]'
,这意味着如果字符串中没有 space,你的程序将崩溃。
除了问题,
函数中int tokenise(char str[], int start, char result[])
int j;
j
未初始化,但随后也在循环中递增。在使用之前将 j
初始化为 0
否则它将具有不确定的值。
同样由于 { }
的错误放置,您的函数 tokenize
定义在 main
中。在 main
之外定义它,这通常是这样做的。
我刚开始学习如何用 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 循环的正上方。 感谢任何帮助,谢谢。
- 无论函数的结果如何,你总是return
-1
。 - 您不需要寻找换行符
'\n'
和其他类似的白色 space 字符。考虑在 ctype.h. 中使用 - 你不寻找字符串的结尾,
'[=13=]'
,这意味着如果字符串中没有 space,你的程序将崩溃。
isspace()
函数
除了问题
函数中int tokenise(char str[], int start, char result[])
int j;
j
未初始化,但随后也在循环中递增。在使用之前将 j
初始化为 0
否则它将具有不确定的值。
同样由于 { }
的错误放置,您的函数 tokenize
定义在 main
中。在 main
之外定义它,这通常是这样做的。