#include <string.h>
char *strstr(const char *haystack, const char *needle);
在字串 haystack(乾草堆)中尋找子字串 needle(針)第一次出現的位置。比較過程不包含結束符 \\0。
haystack:要被搜尋的目標字串。needle:要搜尋的子字串。haystack 中 needle 首次出現位置的指標。needle 未在 haystack 中找到,返回 NULL。needle 為空字串(""),返回 haystack。// strstr_demo.c
#include <stdio.h>
#include <string.h>
int main(void) {
const char *haystack = "Golden Global View";
const char *needle1 = "lob";
const char *needle2 = "Global";
char *pos;
// 情況 1:找到子字串
pos = strstr(haystack, needle1);
if (pos) {
printf("找到 '%s' 於位置: %ld (內容: %s)\n", needle1, pos - haystack, pos);
} else {
printf("未找到 '%s'\n", needle1);
}
// 情況 2:找到單詞
pos = strstr(haystack, needle2);
if (pos) {
printf("找到 '%s' 於位置: %ld (內容: %s)\n", needle2, pos - haystack, pos);
}
// 情況 3:未找到
pos = strstr(haystack, "XYZ");
if (!pos) printf("未找到 'XYZ'\n");
return 0;
}
找到 'lob' 於位置: 5 (內容: lobal View)
找到 'Global' 於位置: 7 (內容: Global View)
未找到 'XYZ'
strstr 區分大小寫。需不區分大小寫搜尋時,可自行實現或使用 strcasestr(POSIX 擴展,非標準 C)。pos - haystack(需確保兩指標指向同一陣列)。NULL 指標會導致未定義行為(通常崩潰),調用前務必確認參數合法。strchr:尋找單一字元首次出現位置。strpbrk:尋找字串中任一字元集合出現的位置。strtok:分割字串(會修改原字串)。strstr 的寬字元版本:wcsstr (<wchar.h>)。