C 語言 strstr 尋找子字串出現次數:while 迴圈模範模式與封裝函數
核心模式
const char *haystack = "abcd1234abcd5678abcd";
const char *needle = "abcd";
int count = 0;
const char *p = haystack;
while ((p = strstr(p, needle)) != NULL) {
++count;
p += strlen(needle); // 移至匹配後,避免重疊匹配 (如 "aaa" 找 "aa")
}
printf("出現 %d 次\n", count); // 3
封裝為通用函數
int count_substr(const char *haystack, const char *needle) {
if (!haystack || !needle) return -1;
if (*needle == '\0') return 0; // 空字串定義
int count = 0;
const char *p = haystack;
size_t nlen = strlen(needle);
while ((p = strstr(p, needle)) != NULL) {
++count;
p += nlen;
}
return count;
}
進階:getCount 含輸出參數
int getCount(const char *haystack, const char *needle, int *out_count) {
if (!haystack || !needle || !out_count) return -1;
*out_count = 0;
const char *p = haystack;
size_t nlen = strlen(needle);
while ((p = strstr(p, needle)) != NULL) {
++(*out_count);
p += nlen;
}
return 0;
}
注意事項
strstr 返回第一次出現位置,若無則 NULL。
p += strlen(needle) 跳過已匹配部分,不支援重疊匹配 (如 "aaaa" 找 "aa" 只算 2 次)。
- 需重疊匹配時,改用
p++ 或 KMP/BM 演算法。
strstr 為線性搜尋,長文本大模式建議用 KMP (O(n+m))。