我有一个带字符串的函数。我复制了一个字符串和char *token;
。我说token = strtok(myString, " ");
然后用while(token != NULL) {...}
开始一个while循环,我在while循环中做了一些事情。在while
循环结束时,我说token = strtok(NULL, " ");
似乎遵循examples I've seen online。我的输入字符串是"这是一个我会搞砸的字符串"我的第一个标记是"这个"这很棒,但之后我说token = strtok(NULL, " ");
令牌似乎是"(null)"而不是"是"。我想知道为什么。这是我的代码:
int numReps2(char *s) {
printf("inside numReps2 with \"%s\"\n", s);
// iterate through s until you find a space
// do matchingwords with the word and an accumulator string that you build char x char
int l = mystrlen(s);
char *copy = malloc(1+(sizeof(char) * l));
mystrcpy(copy, s);
char *accu = malloc(1+(sizeof(char) * l));
int ret = 0;
printf("about to tokenize \"%s\"\n", copy);
char *token;
const char delim[2] = " ";
token = strtok(copy, delim);
while(token != NULL) {
if(matchingWords(accu, copy)) {
printf("match-> accu is \"%s\" and token is \"%s\"\n", accu, token);
// we have a match
ret++;
} else {
// no match, add to accu
char *temp = mystrappend(token, " "); // stick a space after it
printf("no match, adding \"%s\" to \"%s\", token is still \"%s\"\n", temp, accu, token);
accu = mystrappend(accu, temp);
printf("accu is now \"%s\"\n", accu);
free(temp);
printf("after freeing temp, token is \"%s\"\n", token);
}
printf("here is what's after token: %c\n", *(token+strlen(token)+2));
token = strtok(NULL, delim);
printf("just tok'd again, now it's \"%s\"\n", token);
}
free(copy);
free(accu);
return ret;
}