如何检查c上的句子中是否有单词?



例如:str = "我有一个会议"Word = "meet"应该给0,因为没有

这个词我尝试了strstr(str, word),但它检查子字符串,所以这个例子给出了1

我假设单词是由空白字符分隔的字符序列。

您可以使用strstr函数,但是您还需要检查所找到的子字符串之前和之后是否有空白,或者返回的指针是否指向句子的开头,或者所找到的子字符串是否构成句子的尾部。

下面是一个演示程序,展示了如何定义这样一个函数。

#include <stdio.h>
#include <string.h>
#include <ctype.h>
char * is_word_present( const char *sentence, const char *word )
{
const char *p = NULL;

size_t n = strlen( word );

if ( n != 0 )
{
p = sentence;

while ( ( p = strstr( p, word ) ) != NULL )
{
if ( ( p == sentence || isblank( ( unsigned char )p[-1] ) ) &&
( p[n] == ''  || isblank( ( unsigned char )p[n]  ) ) )
{
break;
}
else
{
p += n;
}
}
}

return ( char * )p;
}
int main( void )
{
char *p = is_word_present( "I have a meeting", "meet" );

if ( p )
{
puts( "The word is present in the sentence" );
}
else
{
puts( "The word is not present in the sentence" );
}

p = is_word_present( "I meet you every day", "meet" );

if ( p )
{
puts( "The word is present in the sentence" );
}
else
{
puts( "The word is not present in the sentence" );
}

return 0;
}

程序输出为

The word is not present in the sentence
The word is present in the sentence

相关内容

  • 没有找到相关文章

最新更新