如何计算字符串中有多少个单词?

How to count how many word in string?

我想知道如何计算一个字符串中有多少个单词。 我使用 strstr 进行比较,它有效但只有效一次

像这样

char buff = "This is a real-life, or this is just fantasy";
char op = "is";

if (strstr(buff,op)){
    count++;
}
printf("%d",count);

输出为1但是句子中有两个“是”,请告诉我。

对于初学者来说,你必须至少像

一样编写声明
char buff[] = "This is a real-life, or this is just fantasy";
const char *op = "is";

此外,如果您需要计算单词数,则必须检查单词是否由空格分隔。

您可以通过以下方式完成任务

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

//...

size_t n = strlen( op );
for ( const char *p = buff; ( p = strstr( p, op ) ) != NULL; p += n )
{
    if ( p == buff || isblank( ( unsigned char )p[-1] ) )
    {
        if ( p[n] == '[=11=]' || isblank( ( unsigned char )p[n] ) )
        {
            count++;
        }
    }
}
printf("%d",count);

这是一个演示程序。

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

int main(void) 
{
    char buff[] = "This is a real-life, or this is just fantasy";
    const char *op = "is";
    size_t n = strlen( op );

    size_t count = 0;

    for ( const char *p = buff; ( p = strstr( p, op ) ) != NULL; p += n )
    {
        if ( p == buff || isblank( ( unsigned char )p[-1] ) )
        {
            if ( p[n] == '[=12=]' || isblank( ( unsigned char )p[n] ) )
            {
                count++;
            }
        }
    }

    printf( "The word \"%s\" is encountered %zu time(s).\n", op, count );

    return 0;
}

程序输出为

The word "is" is encountered 2 time(s).

循环中解析字符串。

由于 OP 有“但句子中有两个“是””,仅查找 "is" 是不够的,因为它在 "This" 中出现了 4 次,两次。代码需要解析字符串以获得“单词”的概念。

区分大小写也是一个问题。

char buff = "This is a real-life, or this is just fantasy";
char op = "is";

char *p = buff;
char *candidate;
while ((candidate = strstr(p, op)) {
  // Add code to test if candidate is a stand-alone word
  // Test if candidate is beginning of buff or prior character is a white-space.
  // Test if candidate is end of buff or next character is a white-space/punctuation.
  p += strlen(op); // advance
}

对我来说,我不会使用 strstr(),而是使用 isalpha() 寻找“单词”。

// Concept code
size_t n = strlen(op);
while (*p) {
  if (isalpha(*p)) {  // Start of word
    // some limited case insensitive compare
    if (strnicmp(p, op, n) == 0 && !isalpha(p[n]) {  
      count++;
    }
    while (isalpha(*p)) p++;  // Find end of word
  } else {
    p++;
  }
}