[英]Match exact string with strstr
假設我有以下字符串:
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”這個詞?
搜索“in”; 注意空格。 然后考慮以“in”開頭並以“in”結尾的句子的邊緣情況。
另一種方法是:
在整個句子上使用strtok()
,空格作為分隔符。
所以現在你可以檢查你的令牌“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
的檢查。
添加一個isdelimiter()
來檢查strstr()
的前后結果。
// Adjust as needed.
int isdelimiter(char ch) {
return (ch == ' ') || (ch == '\0');
}
int MatchAlex(const char *haystack, const char *needle) {
int match = 0;
const char *h = haystack;
const char *m;
size_t len = strlen(needle);
while ((m = strstr(h, needle)) != NULL) {
if ((m == haystack || isdelimiter(m[-1])) && isdelimiter(m[len])) {
// printf("'%s'",m);
match++;
h += len;
} else {
h++;
}
}
return match;
}
int main(void) {
printf("%d\n",
MatchAlex("in the interior of the inside is an inner inn xxin", "in"));
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.