非常教程

C参考手册

字符串 | Strings

strstr

在头文件<string.h>中定义

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):
    • 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函数

扩展内容

strchr

找到第一个出现的字符(函数)

strrchr

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

| strstr 的C ++文档|

C

C 语言是一门通用计算机编程语言,应用广泛。C 语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。