【问题标题】:How do I check if a word is in sentence on C如何检查一个单词是否在 C 的句子中
【发布时间】:2021-12-11 08:08:12
【问题描述】:

例如: str = "我要开会" 词=“见面” 应该给0,因为没有这样的词

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

【问题讨论】:

  • 使用stktok(),将结果放入数组中,然后检查单词是否匹配数组中的任何单词
  • 或者strstr() 返回一个指向比赛开始的指针,因此从那时起检查之前和之后的内容很容易。
  • 这能回答你的问题吗? Check substring exists in a string in C
  • 是的,我看到了,在那里找不到解决方案。我会尝试执行@Frank 的建议

标签: c search substring c-strings function-definition


【解决方案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] == '\0'  || 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

【讨论】:

    猜你喜欢
    • 2019-01-06
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多