C

strstr

strstr

在头文件中定义
char * strstr(const char * str,const char * substr);

查找由str指向的以null结尾的字节字符串中由substr指向的以null结尾的字节字符串的第一次出现。 不会比较终止的空字符。

如果str或substr不是指向以空字符结尾的字节字符串的指针,则行为未定义。

参数

str-指向要检查的以null结尾的字节字符串
substr-指向要以空字符结尾的字节字符串进行搜索的指针

返回值

指向str中找到的子字符串的第一个字符的指针,如果没有找到这样的子字符串,则返回NULL。 如果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标准(ISO / IEC 9899:2011):

扩展内容

strchr找到第一个出现的字符(函数)
strrchr查找最后一次出现的字符(函数)

| strstr 的C ++文档|