命名空间
变体
操作

strstr

出自 cppreference.cn
< c‎ | string‎ | byte
定义于头文件 <string.h>
char* strstr( const char* str, const char* substr );
(1)
/*QChar*/* strstr( /*QChar*/* str, const char* substr );
(2) (自 C23 起)
1)str 所指向的空终止字节字符串中,查找 substr 所指向的空终止字节字符串的首次出现。不比较终止空字符。
2) 等价于 (1) 的类型泛型函数。设 T 为非限定字符对象类型。
  • str 的类型为 const T*,则返回类型为 const char*
  • 否则,若 str 的类型为 T*,则返回类型为 char*
  • 否则,行为未定义。
若抑制每个这些泛型函数的宏定义以访问实际函数(例如,若使用 (strstr) 或函数指针),则实际函数声明 (1) 变为可见。

strsubstr 并非指向空终止字节字符串的指针,则行为未定义。

内容

[编辑] 参数

str - 指向要检查的空终止字节字符串的指针
substr - 指向要搜索的空终止字节字符串的指针

[编辑] 返回值

指向在 str 中找到的子字符串的首字符的指针;若未找到此类子字符串,则为空指针。若 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 函数 (页码:待定)
  • C17 标准 (ISO/IEC 9899:2018)
  • 7.24.5.7 strstr 函数 (页码:269)
  • C11 标准 (ISO/IEC 9899:2011)
  • 7.24.5.7 strstr 函数 (页码:369)
  • C99 标准 (ISO/IEC 9899:1999)
  • 7.21.5.7 strstr 函数 (页码:332)
  • C89/C90 标准 (ISO/IEC 9899:1990)
  • 4.11.5.7 strstr 函数

[编辑] 参见

查找字符的首次出现
(函数) [编辑]
查找字符的最后一次出现
(函数) [编辑]
C++ 文档 关于 strstr