首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 標準庫函數詳解:strstr — 尋找子字串首次出現位置

     編輯:關於C語言

函數原型

#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'

常見陷阱與注意事項

  1. 大小寫敏感:strstr 區分大小寫。需不區分大小寫搜尋時,可自行實現或使用 strcasestr(POSIX 擴展,非標準 C)。
  2. 指標運算:返回值為指標,若需索引值,需計算 pos - haystack(需確保兩指標指向同一陣列)。
  3. 空指標安全:傳入 NULL 指標會導致未定義行為(通常崩潰),調用前務必確認參數合法。

相關函數

  • strchr:尋找單一字元首次出現位置。
  • strpbrk:尋找字串中任一字元集合出現的位置。
  • strtok:分割字串(會修改原字串)。
  • strstr 的寬字元版本:wcsstr (<wchar.h>)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved