我試圖標記一個sting,這裏是我的嘗試。使用指針標記字符串
char new_str[1024];
void tokenize_init(const char str[]){//copy the string into global section
strcpy(new_str,str);
}
int i = 0;
char *tokenize_next() {
const int len = strlen(new_str);
for(; i <= len; i++) {
if (i == len) {
return NULL;
}
if ((new_str[i] >= 'a' && new_str[i] <= 'z') ||
(new_str[i] >= 'A' && new_str[i] <= 'Z')) {
continue;
}else {
new_str[i] = '\0';
i = i + 1;
return new_str;
}
}
return NULL;
}
//main function
int main(void) {
char sentence[] = "This is a good-sentence for_testing 1 neat function.";
printf("%s\n", sentence);
tokenize_init(sentence);
for (char *nt = tokenize_next();
nt != NULL;
nt = tokenize_next())
printf("%s\n",nt);
}
但是,它只是打印出句子的第一個單詞(即「This」),然後停止。有人能告訴我爲什麼嗎?我的猜測是我的new_str不是持久化的,當主函數調用tokenize_next()時,new_str變成了句子的第一個單詞。提前致謝。
是否有任何特定的原因導致您不僅僅使用'strtok()'來標記字符串? –
http://www.elook.org/programming/c/strtok.html可能會有所幫助 – 2013-07-15 18:35:12
「strsep」不是新的熱點嗎? –