想要从双指针传递单个char指针
我必须编写一个函数,它接受2个双指针(都是char类型)。 第一个双指针有一串查询值,第二个指针有停用词。 我们的想法是从查询字符串中删除停用词并返回没有这些停用词的所有单词。
例如
输入 – 查询:“the”,“new”,“store”,“in”,“SF”
stopwords: “the”, “in”
OUTPUT新店SF
我在尝试使用strtok时编写了以下代码,它只接受char类型的单个指针。 如何访问双指针的内容?
谢谢
#include void remove_stopwords(char **query, int query_length, char **stopwords, int stopwords_length) { char *final_str; final_str = strtok(query[0], stopwords[0]); while(final_str != NULL) { printf("%s\n", final_str); final_str = strtok(NULL, stopwords); } }
为简单起见,你可以假设一个双指针相当于一个2d数组(它不是!)。 但是,这意味着您可以使用array-convention来访问双指针的内容。
#include #include char *query[5] = {"the","new","store","in","SF"}; char *stopwords[2] = {"the","in"}; char main_array[256]; void remove_stopwords(char **query,int query_length, char **stopwords, int stopwords_length); int main() { remove_stopwords(query,5,stopwords,2); puts(main_array); return 0; } void remove_stopwords(char **query,int query_length, char **stopwords, int stopwords_length) { int i,j,found; for(i=0;i
输出: new store SF newstoreSF
@Binayaka Chakraborty的解决方案解决了这个问题,但我认为提供一个仅使用指针并显示正确使用strtok()
的替代方案可能是有用的, strtok()
的使用可能在问题中被误解了。
特别是, strtok()
的第二个参数是一个指向字符串的指针,该字符串列出了要使用的所有单字符分隔符。 不能使用strtok()
根据多字符分隔符拆分字符串,这似乎是问题的意图。
#include #include #include void remove_stopwords(char *query, char **stopwords) { char *final_str = strtok(query, " "); while(final_str != NULL) { int isStop = 0; char **s; for (s = stopwords; *s; s++) { if (strcmp(final_str,*s) == 0) { isStop = 1; } } if (!isStop) printf("%s ", final_str); final_str = strtok(NULL, " "); } } int main() { const char *q = "the new store in SF"; char *query = malloc(strlen(q)+1); /* We copy the string before calling remove_stopwords() because strtok must be able to modify the string given as its first parameter */ strcpy(query,q); char *stopwords[] = {"the", "in", NULL}; remove_stopwords(query,stopwords); return 0; }
这里显示的方法还避免了对所涉及的arrays的大小进行硬编码的需要,因此减少了错误的可能性。