这是在 Ansi C 中。我得到了一个字符串。我应该创建一个方法,该方法返回指向所述字符串的每个单词开头的字符指针数组。我不允许使用 Malloc,而是告诉我输入的最大长度为 80。
此外,在有人因为我没有搜索论坛而抨击我之前,我不能使用 strtok :(
char input[80] = "hello world, please tokenize this string"
方法的输出应该有 6 个元素;
output[0] points to the "h",
output[1] points to the "w",
等等。
方法应该怎么写?
此外,我需要一种类似的方法来处理来自最多 110 行的文件的输入。
伪代码:
boolean isInWord = false
while (*ptr != NUL character) {
if (!isInWord and isWordCharacter(*ptr)) {
isInWord = true
save ptr
} else if (isInWord and !isWordCharacter(*ptr)) {
isInWord = false
}
increment ptr
}
isWordCharacter
检查字符是否是单词的一部分。根据您的定义,它可以只是字母字符(将 part-time
识别为 2 个单词),或者它可能包含 -
(将 part-time
识别为一个单词)。
因为这是家庭作业,所以这是您可能需要的一部分:
char* readPtr = input;
char* wordPtr = input;
int wordCount = 0;
while (*readPtr++ != ' ');
/* Here we have a word from wordPtr to readPtr-1 */
output[wordCount++] = /* something... :) */
你需要在一个循环中,并且必须考虑如何移动到下一个单词,并检查输入的结尾。