[英]Tokenize String by using pointer
我正在嘗試標記刺,這是我的嘗試。
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只是句子的第一個單詞。 提前致謝。
之所以只打印“ This”,是因為您迭代到第一個非字母字符,而該字符恰好是一個空格,並在此行將其替換為空終止符:
new_str[i] = '\0';
在那之后,您對字符串的其余部分做什么都無所謂,它只會打印到那一點。 下次調用tokenize_next時,字符串的長度不再是您想的那樣,因為它僅計算單詞“ This”,並且由於“ i”已經達到該數量,因此該函數返回,並且每次后續調用都會返回:
if ( i == len)
{
return NULL;
}
要修復此功能,您將需要以某種方式更新指針,以使其在下一次迭代中越過該字符。
但是,這很麻煩。 使用上面提到的功能之一(例如strtok或strsep)會更好
更新:
如果無法使用這些功能,則重新設計功能將是理想的選擇,但是,根據您的要求,請嘗試以下修改:
#include <string.h>
#include <cstdio>
char new_str[1024];
char* str_accessor;
void tokenize_init(const char str[]){//copy the string into global section
strcpy(new_str,str);
str_accessor = new_str;
}
int i = 0;
char* tokenize_next(void) {
const int len = strlen(str_accessor);
for(i = 0; i <= len; i++) {
if ( i == len) {
return NULL;
}
if ((str_accessor[i] >= 'a' && str_accessor[i] <= 'z') ||
(str_accessor[i] >= 'A' && str_accessor[i] <= 'Z')) {
continue;
}
else {
str_accessor[i] = '\0';
char* output = str_accessor;
str_accessor = str_accessor + i + 1;
if (strlen(output) <= 0)
{
str_accessor++;
continue;
}
return output;
}
}
return NULL;
}
//main function
int main(void) {
char sentence[] = "This is a good-sentence for_testing 1 neater function.";
printf("%s\n", sentence);
tokenize_init(sentence);
for (char *nt = tokenize_next(); nt != NULL; nt = tokenize_next())
printf("%s\n",nt);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.