2014-12-06 73 views
2
的strstr匹配

精確串假設我有以下字符串:

in the interior of the inside is an inner inn 

,我想搜索,比方說,對於「中」(多久「在」出現)的出現次數。

在我的程序中,我用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」?

+1

你想說只有一個「in」嗎? – 2014-12-06 16:20:00

+0

在這種情況下,是的,只有一個單詞「in」。 但是對於字符串:「in inside inside in in」,有3個。 – Alex 2014-12-06 16:26:48

回答

2

請嘗試以下

#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字符串可以包含puctuations。

+0

我看到我的回答很符合你的邏輯。 +1這個早期的答案。 – chux 2014-12-06 16:48:21

+0

@chux直接的方法看起來類似。 – 2014-12-06 16:53:00

2

搜索「in」;注意空格。然後考慮以「in」開始並以「in」結尾的句子的邊緣案例。做

+0

如果單詞之間用逗號,點,感嘆號等分隔,該怎麼辦? – Alex 2014-12-06 16:19:16

+0

呃,就像我說的那樣,這是規格的改變!這對初學者會有幫助。實際上,使用正則表達式庫。 – Bathsheba 2014-12-06 16:19:41

2

另一種方式是:

使用strtok()你的整個句子與空間分隔符。

所以,現在你可以檢查你對令牌「中的」

+0

這個工作是否適用於「xxin」? 'strtok()'適用於尾隨分隔符,但不適用於前導分隔符。 – chux 2014-12-06 16:21:05

+0

'strtok()'會導致未定義的行爲,如果它咀嚼只讀字符串像const char * foo =「我有麻煩」 – Bathsheba 2014-12-06 16:22:32

+0

@chux對於給定的句子,這將工作,也意味着如果你想檢查你的句子中的「in」,那麼這將工作 – Gopi 2014-12-06 16:22:35

1

添加一個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; 
}