/* finds the next instance of needle in haystack
zbpos: the zero-based position to begin searching from
haystack: the string to search in
needle: the string that must be found
returns the next match of `needle` in `haystack`, or -1 if not found
*/
int findnext(int zbpos, const char *haystack, const char *needle)
{
char *p;
if (((p = strstr(haystack + zbpos, needle)) != NULL)
return p - haystack;
return -1;
}
strstr
searches the haystack
(first) argument for the string pointed to by needle
. If found, strstr
returns the address of the occurrence. If it could not find needle
, it returns NULL. We use zbpos
so that we don't keep finding the same needle over and over again. In order to skip the first instance, we add an offset of zbpos
. A Notepad clone might call findnext
like this, in order to implement its "Find Next" dialogue:
/*
Called when the user clicks "Find Next"
doc: The text of the document to search
findwhat: The string to find
*/
void onfindnext(const char *doc, const char *findwhat)
{
static int i;
if ((i = findnext(i, doc, findwhat)) != -1)
/* select the text starting from i and ending at i + strlen(findwhat) */
else
/* display a message box saying "end of search" */
}