我有一个字符串数组。
例如: -
array[0] = "book floor garden bank autumn";
array[1] = "daisy food yatch beach lottery";
char comp[];
我需要在循环中使用strcmp()
将每个索引的第一个单词(例如: - book,daisy ...等)与字符串(例如: - comp)进行比较。
问题是,是否有一种从字符串中检索第一个单词的简单方法。
有strtok
是否可行,或者是否有任何内置方法可以提供帮助。
这是我的任务的一部分,我只需要一个例子或建议如何完成。
答案 0 :(得分:0)
#include <stdio.h>
#include <string.h>
int main(){
char *array[2];
char comp[] = "daisy";
int i;
array[0] = "book floor garden bank autumn";
array[1] = "daisy food yatch beach lottery";
for(i=0;i<2;++i){
char *p = strchr(array[i], ' ');
if(!p)
p = strchr(array[i], '\0');
size_t len = p - array[i];
char first_word[len+1];
memcpy(first_word, array[i], len);
first_word[len]=0;
if(strcmp(first_word, comp)==0){
puts("found it!!");
}
}
return 0;
}
答案 1 :(得分:-1)
strtok对此很好,你应该做类似的事情:
#include <string.h>
int i = 0;
char *token;
int different;
while(i < size){
token = strtok(array[i], " ");
different = strcmp(word, token);
if(different){
//do something
}
i++;
}