计算字符串中特定单词的出现次数

标签 c substring c-strings counting function-definition

这个函数的问题在于它会处理所有的子字符串,但不会查找单词,例如如果我在“hifive to to evereyone”中查找“hi”,它会返回 1

int HowManyString(char *satz,char *word) {
    int coun = 0;
    while (strlen(word)<strlen(satz)) {
        if (strstr(satz,word)==NULL) {
            return coun;
        } else {
            satz=strstr(satz,word)+strlen(word);
            if(*(satz)==' '||*(satz)=='\0'){
                coun++;
            } else {
                return coun;
            }
        }
    }
    return coun;
}

最佳答案

将您的方法与标准函数一起使用 strstr您的函数可以看起来像下面的演示程序所示

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

size_t HowManyString( const char *s1, const char *s2 )
{
    size_t count = 0;

    size_t n = strlen( s2 );

    for ( const char *p = s1; ( p = strstr( p, s2 ) ) != NULL; p += n )
    {
        if ( ( p == s1 || isblank( ( unsigned char )p[-1] ) ) &&
             ( p[n] == '\0' || isblank( ( unsigned char )p[n] ) ) )
        {
            ++count;
        }            
    }

    return count;
}

int main( void )
{
    const char *s1 = "hifive";
    const char *s2 = "hi";

    printf( "%zu\n", HowManyString( s1, s2 ) );

    s1 = "fivehi";

    printf( "%zu\n", HowManyString( s1, s2 ) );

    s1 = "hi five";

    printf( "%zu\n", HowManyString( s1, s2 ) );

    s1 = "five hi";

    printf( "%zu\n", HowManyString( s1, s2 ) );
}

程序输出为

0
0
1
1

如果源字符串可以包含换行符'\n'在函数中使用 isspace而不是 isblank .

关于计算字符串中特定单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73182855/

相关文章:

c++ - 'memchr' 的冲突类型

python - C和Python之间的套接字通信

c - 如何打印程序执行的次数?

python - 通过分隔符计数和位置从数据框中提取特定文本

arrays - 在 C 的 while 循环中迭代 *str 与 str[]

c++ - 警告 - 从 size_t 转换为 DWORD,可能丢失数据

c - _malloc 在汇编中到底做了什么?

mysql_real_escape_string 在输出中包括斜杠(C,不是 PHP)

SQL 字符串用逗号和空格分割

regex - Postgres : Extract the last substring in a string