名稱空間
變體
操作

strstr

來自 cppreference.com
< c‎ | string‎ | byte
定義於標頭檔案 <string.h>
char* strstr( const char* str, const char* substr );
(1)
/*QChar*/* strstr( /*QChar*/* str, const char* substr );
(2) (自 C23 起)
1) 查詢在 null 結尾的位元組字串 str 中,首次出現的 null 結尾的位元組字串 substr。不比較終止 null 字元。
2) 型別通用函式,等同於 (1)。令 T 為不合格字元物件型別。
  • 如果 str 的型別是 const T*,則返回型別是 const char*
  • 否則,如果 `str` 的型別為 `T*`,則返回型別為 `char*`。
  • 否則,行為未定義。
如果抑制這些通用函式的每個宏定義以訪問實際函式(例如,如果使用 (strstr) 或函式指標),則實際函式宣告 (1) 變得可見。

如果 strsubstr 不是指向 null 結尾的位元組字串的指標,則行為未定義。

目錄

[編輯] 引數

str - 指向要檢查的 null 結尾的位元組字串的指標
substr - 指向要搜尋的 null 結尾的位元組字串的指標

[編輯] 返回值

指向 str 中找到的子字串的第一個字元的指標,如果未找到此類子字串,則為 null 指標。如果 substr 指向空字串,則返回 str

[編輯] 示例

#include <stdio.h>
#include <string.h>
 
void find_str(char const* str, char const* substr)
{
    char const* pos = strstr(str, substr);
    if (pos)
        printf(
            "Found the string [%s] in [%s] at position %td\n",
            substr, str, pos - str
        );
    else
        printf(
            "The string [%s] was not found in [%s]\n",
            substr, str
        );
}
 
int main(void)
{
    char const* str = "one two three";
    find_str(str, "two");
    find_str(str, "");
    find_str(str, "nine");
    find_str(str, "n");
 
    return 0;
}

輸出

Found the string [two] in [one two three] at position 4
Found the string [] in [one two three] at position 0
The string [nine] was not found in [one two three]
Found the string [n] in [one two three] at position 1

[編輯] 參考

  • C23 標準 (ISO/IEC 9899:2024)
  • 7.24.5.7 strstr 函式 (p: TBD)
  • C17 標準 (ISO/IEC 9899:2018)
  • 7.24.5.7 strstr 函式 (p: 269)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.24.5.7 strstr 函式 (p: 369)
  • C99 標準 (ISO/IEC 9899:1999)
  • 7.21.5.7 strstr 函式 (p: 332)
  • C89/C90 標準 (ISO/IEC 9899:1990)
  • 4.11.5.7 strstr 函式

[編輯] 另請參見

查詢字元的第一次出現
(函式) [編輯]
查詢字元的最後一次出現
(函式) [編輯]
C++ 文件 for strstr