当前位置: C语言 -- 标准库 -- <string.h> -- strstr

strstr函数


概要:
#include <string.h>
char *strstr(const char *s1, const char *s2);

描述:

该函数搜索参数s2指向字符串中的字符序列(不包括终止空字符。)在参数s1指向字符串中第一次出现的位置。


参数:
const char *s1

指向字符串的指针。

const char *s2

指向子字符串的指针。


返回值:

如果参数s1指向字符串中不存在要搜索的字符序列,函数返回空指针;否则函数返回指向第一个匹配成功的字符序列的指针。

如果参数s2指向字符串的长度为0,函数返回s1


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
/*函数strstr范例*/

#include <stdio.h>
#include <string.h>

int main(void)
{
    const char strOne[] = "You can fool all the people some of the time,\
                and some of the people all the time,\
                but you can not fool all the people all the time.";
    const char strTwo[] = "the";
    const char *ptr = strOne;
    int count = 0;

    /*统计单词the出现的次数。*/
    while(ptr = strstr(ptr, strTwo))
    {
        ++count;
        ptr += strlen(strTwo);
    }
    printf("Total %d time%s.\n", count, (count>1)?"s":"");
    
    return 0;
}


输出:

Total 6 times.


相关内容:
memchr 搜索指定字符在内存区域第一次出现位置的函数。
strchr 搜索指定字符在字符串中第一次出现位置的函数。
strcspn 计算最大初始片段长度的函数。
strpbrk 搜索字符在字符串中第一次出现位置的函数。
strrchr 搜索指定字符在字符串中最后一次出现位置的函数。
strspn 计算最大初始片段长度的函数。
strtok 拆分字符串的函数。