strstr 在 <string.h> 中宣告:char* strstr(const char* haystack, const char* needle)。回傳 needle 在 haystack 首次出現位址,找不到回傳 NULL。needle 為空串時回傳 haystack。
needle 結尾 \0 的比對char* my_strstr(char* s1, char* s2) {
if (!*s2) return s1; // 空 needle
while (*s1) {
int n = 0;
for (; *(s1+n) == *(s2+n); n++) {
if (!*(s2+n+1)) return s1; // 完全匹配
}
s1++;
}
return NULL;
}
char* strstr(char* buf, char* sub) {
if (!*sub) return buf;
while (*buf) {
char* bp = buf;
char* sp = sub;
do {
if (!*sp) return buf;
} while (*bp++ == *sp++);
buf++;
}
return NULL;
}
const char* isSub(const char* str, const char* sub) {
if (!*sub) return str;
for (const char* s = str; *s; s++) {
const char* s1 = s;
const char* s2 = sub;
while (*s1 && *s2 && *s1 == *s2) { s1++; s2++; }
if (!*s2) return s; // sub 走完 = 找到
}
return NULL;
}
| haystack | needle | 預期結果 | 說明 |
|---|---|---|---|
| "Golden Global View" | "ob" | "obal Global View" | 正常匹配 |
| "abc" | "" | "abc" | 空 needle 回傳 haystack |
| "abc" | "d" | NULL | 不存在 |
| "aaaaa" | "aaa" | "aaaaa" | 重疊匹配,回傳第一個 |
| "" | "a" | NULL | 空 haystack |
strstr 標準庫(通常已優化)或 KMP/BM 演算法strcasestr(POSIX 擴展)或轉大小寫後搜尋std::string::find 或 std::search