strstr:在字符串中查找指定字符串的第一次出现:
不需要调用其他库函数做法:
- char* strstr(const char *s1, const char *s2)
- {
- int n;
- if (*s2)
- {
- while (*s1)
- {
- for (n=0; *(s1 + n) == *(s2 + n); n++)
- {
- if (!*(s2 + n + 1))
- return (char *)s1;
- }
- s1++;
- }
- return NULL;
- }
- else
- return (char *)s1;
- }
调用了一次include <string.h> 中的strncmp
- char *mystrstr( const char *s1, const char *s2 )
- {
- int len2;
- if ( !(len2 = strlen(s2)) )
- return (char *)s1;
- for ( ; *s1; ++s1 )
- {
- if ( *s1 == *s2 && strncmp( s1, s2, len2 )==0 )
- return (char *)s1;
- }
- return NULL;
- }