2013-07-02 24 views
1

美好的一天,的strstr找到用c返回true所有的时间

所以我决定再去槽我的C和开始做一个简单的搜索字符串中的单词串词。

这里是我的代码:

#include<stdio.h> 
#include<conio.h> 
#include<string.h> 

main(){ 
char word[100]; 
char sentence[100]; 

clrscr(); 
printf("Enter a word: "); 
fgets(word, 100, stdin); 
getch(); 
printf("The word is : %s", &word); 
getch(); 
printf("\nEnter a sentence: "); 
fgets(sentence, 100, stdin); 
getch(); 
printf("The sentence is: %s",&sentence); 
getch(); 
if(strstr(sentence,word) == 0){ 
    printf("word found!"); 
} 
getch(); 
return 0; 
} 

现在的问题是,每当我试图使用strstr字符串搜索词,它总是返回字发现。我也尝试过使用strcmp,但那只会比较字符串的第一个实例,并且当没有找到匹配时会停止,因此如果您想在字符串问题中搜索某个单词,那么这并不可取。

我以前没有真正做过这样的程序,实际上从来没有需要过。那么我可以问为什么工作不正常,因为根据其描述strstr应该是在一个句子中搜索一个词,或者我是否误解了它。

此外,如果您对我的程序有任何意见,请随时说出来,以便我可以意识到我的错误。

谢谢

举例: 字:狗
一句:狗是这里
应返回true

+0

您打印错误'的printf( “这句话是:%S”,与句子);' – 2013-07-02 09:40:04

+0

@Armin我对不起,但这不是我写的吗? – magicianiam

+0

是的。我正在指出。 – 2013-07-02 09:42:52

回答

4

此行

if(strstr(sentence,word) == 0) 

应该是

if(strstr(sentence,word) != NULL) 

strstr()sentenceNULL如果瓦特返回指向的word第一次出现ord没有找到。

详情please read here


另外使用fgets()在“字符串”阅读附加一个'\n'以“串”的结束。这禁止成功的比较。

砍后'\n'的,你可以这样做:

fgets(word, sizeof(word), stdin); 
{ 
    size_t size = strlen(word); 

    if (size && ('\n' == word[size-1])) 
    { 
    word[size-1] = '\0'; 
    } 
} 
+0

美好的一天@ alk,我试过了,它仍然没有工作,它只有当这个词可以在句子的开头找到时才起作用。 – magicianiam

+0

作为fgets的替代选择,你会有什么建议? – magicianiam

+0

@magicianIam:没有,使用'fgets()'是一个安全的选择,你在做什么。 – alk

2

返回指向STR2赛车第一次出现在STR1,或如果str2不是str1的一部分,则为空指针。

返回NULL(0)本质上意味着该字符串未找到。

因此

if(strstr(sentence,word) == 0){ 
    printf("word found!"); 
} 

应该

if(strstr(sentence,word) != NULL){ 
    printf("word found!"); 
} 

来源 - http://en.cppreference.com/w/c/string/byte/strstr

此外作为阿明指出的那样,你不应该使用地址操作,&,在你printf%s期望有一个指针传递给printf和使用阵列作为sentence的名称实际上是相同的指针数组的开始,即sentence == &sentence[0]

+1

为什么downvote? –

1

strstr()函数查找字符串“针”的第一次出现在字符串“大海捞针”,并将其返回的指针开始子字符串或NULL如果未找到。

所以你的if语句应该是

if(strstr(sentence,word) != NULL){ 
printf("word found"); 
} 

数组名代表它自己的基址,所以写

printf("%s",&word) 

printf("%s",word) 

阵列的两个可叫做基址。

0

。在你的代码,即一点点修正,

if(strstr(sentence,word) == 0){ 
printf("word found!"); 
} 

变化是:代替== 0 = 0,这相当于= NULL, 在三分球的情况下,0和NULL都一样! 。 因为NULL关键字定义为:

#define NULL ((void *)0) 

所以更改您的代码

if(strstr(sentence,word) != 0){ 
printf("word found!"); 
}