69,382
社区成员
发帖
与我相关
我的任务
分享
/* Referenced from Microsoft CRT source code,
efficient and easy to understand */
char* strstr(const char* cs, const char* ct)
{
char* cp = (char*)cs;
char* s1, * s2;
if ( !*ct )
return (char*)cs;
while ( *cp )
{
s1 = cp;
s2 = (char*)ct;
while ( *s1 && *s2 && *s1==*s2) )
++s1, ++s2;
if ( !*s2 )
return cp;
++cp;
}
return NULL;
}
Example
/* STRSTR.C */
#include <string.h>
#include <stdio.h>
char str[] = "lazy";
char string[] = "The quick brown dog jumps over the lazy fox";
char fmt1[] = " 1 2 3 4 5";
char fmt2[] = "12345678901234567890123456789012345678901234567890";
void main( void )
{
char *pdest;
int result;
printf( "String to be searched:\n\t%s\n", string );
printf( "\t%s\n\t%s\n\n", fmt1, fmt2 );
pdest = strstr( string, str );
result = pdest - string + 1;
if( pdest != NULL )
printf( "%s found at position %d\n\n", str, result );
else
printf( "%s not found\n", str );
}
Output
String to be searched:
The quick brown dog jumps over the lazy fox
1 2 3 4 5
12345678901234567890123456789012345678901234567890
lazy found at position 36