This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.
Released under the GNU General Public License.
strstr
Prototype
#include <string.h>
char *strstr(const char *s, const char *substr);
Description
Returns a pointer to the first occurrence of the substring substr
in the string s
.
The terminating null characters are not compared. If the substring
is not found, strstr
returns NULL
. If substr
points to a string with zero length, strstr
returns the s
string.
Implementation
#include <string.h>
char *strstr(const char *s, const char *substr)
{
if (*substr == '\0')
return (char *)s;
for (; (s = strchr(s, *substr)) != NULL; ++s) {
const char *sp1 = s, *sp2 = substr;
for (;;)
if (*++sp2 == '\0')
return (char *)s;
else if (*++sp1 != *sp2)
break;
}
return NULL;
}
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINELEN 1024
/*
* grep.c: find the matches of the user specified string in
* the standard input.
* usage: grep <string>
*/
int main(int argc, char **argv)
{
char buf[MAXLINELEN];
int lineno = 1;
if (argc != 2) {
fprintf(stderr, "usage: %s <string>\n", argv[0]);
return EXIT_FAILURE;
}
while (fgets(buf, MAXLINELEN, stdin) != NULL) {
if (strstr(buf, argv[1]) != NULL)
printf("%s:%d: %s", argv[0], lineno, buf);
++lineno;
}
return EXIT_SUCCESS;
}
References
ISO C 9899:1990 7.11.5.7