这个函数的问题在于它会处理所有的子字符串,但不会查找单词,例如如果我在“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/