C 语言中strstr函数实例详解
strstr函数
strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL
1
2
3
|
const char * strstr ( const char * str1, const char * str2); char * strstr ( char * str1, const char * str2); |
库中实现的strstr
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <stdio.h> #include <string.h> int main () { char str[] = "This is a simple string" ; char * pch; pch = strstr (str, "simple" ); strncpy (pch, "sample" ,6); puts (str); return 0; } |
模拟实现strstr函数
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
26
27
28
29
30
|
const char * My_strstr( const char * str1, const char * str2) { assert (str1); assert (str2); while (*str1 != '\0' ) { const char * p1 = str1; const char * p2 = str2; while ((*p1 != '\0' ) && (*p2 != '\0' ) && (*p1 == *p2)) { ++p1; ++p2; } if (*p2 == '\0' ) { return str1; } ++str1; } return NULL; } int main() { char str1[] = "a wwww qqqqqqqqqqqqqqq" ; char str2[] = "www" ; printf ( "%s\n" , My_strstr(str1, str2)); system ( "pause" ); return 0; } |
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/weixin_36125166/article/details/74025182