CppDS.com

C++ 98 11 14 17 20 手册

strstr

来自cppreference.com
< c‎ | string‎ | byte
定义于头文件 <string.h>
char *strstr( const char* str, const char* substr );

查找 substr 所指的空终止字节字符串在 str 所指的空终止字节字符串中的首次出现。不比较空终止字符。

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

参数

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

返回值

指向于 str 中找到的子串首字符的指针,或若找不到该子串则为空指针。若 substr 指向空字符串,则返回 str

示例

#include <string.h>
#include <stdio.h>
 
void find_str(char const* str, char const* substr) 
{
    char* pos = strstr(str, substr);
    if(pos) {
        printf("found the string '%s' in '%s' at position: %ld\n", substr, str, pos - str);
    } else {
        printf("the string '%s' was not found in '%s'\n", substr, str);
    }
}
 
int main(void) 
{
    char* 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

引用

  • C11 standard (ISO/IEC 9899:2011):
  • 7.24.5.7 The strstr function (p: 369)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.21.5.7 The strstr function (p: 332)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.11.5.7 The strstr function

参阅

查找字符的首次出现
(函数)
查找字符的最后一次出现
(函数)
关闭