假设我有以下字符串:
in the interior of the inside is an inner inn
我想搜索“in”的出现次数(“in”出现的频率)。
在我的程序中,我使用了 strstr 来这样做,但它返回了误报。它将返回:
- in the interior of the inside is an inner inn
- interior of the inside is an inner inn
- inside is an inner inn
- inner inn
- inn
这样认为“in”出现了5次,显然是不正确的。
我应该如何进行才能专门搜索“in”这个词?
最佳答案
尝试以下操作
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char *s = "in the interior of the inside is an inner inn";
char *t = "in";
size_t n = strlen( t );
size_t count = 0;
char *p = s;
while ( ( p = strstr( p, t ) ) != NULL )
{
char *q = p + n;
if ( p == s || isblank( ( unsigned char ) *( p - 1 ) ) )
{
if ( *q == '\0' || isblank( ( unsigned char ) *q ) ) ++count;
}
p = q;
}
printf( "There are %zu string \"%s\"\n", count, t );
return 0;
}
输出是
There are 1 string "in"
如果源字符串可以包含标点符号,您还可以添加对 ispunct
的检查。
关于c - 将精确的字符串与 strstr 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27333631/