strstr

suggest change
#include <string.h>

/* Find the next instance of needle in haystack.
   zbpos: zero-based position at which to start.
   Returns the index of the match, or -1 if there is none.
   The index is assumed to fit in int. */
int findnext(int zbpos, const char *haystack, const char *needle)
{
    char *p;
    size_t len = strlen(haystack);

    if (zbpos < 0)
        zbpos = 0;
    if ((size_t)zbpos > len)
        return -1;

    p = strstr(haystack + zbpos, needle);
    if (p != NULL)
        return (int)(p - haystack);

    return -1;
}

strstr searches haystack for the string pointed to by needle. On a match it returns a pointer to that occurrence; otherwise it returns a null pointer. Adding zbpos starts the search later in the string. The addition is defined only when zbpos is within the array, which the test above enforces. An empty needle matches at the starting position.

A later search must start after the previous match. Starting at the same index finds that match again. Passing the -1 “not found” result as the next offset would form a pointer outside the array, which is undefined behavior.

#include <string.h>

/* Called when the user clicks "Find Next". */
void onfindnext(const char *doc, const char *findwhat)
{
    static int i;

    i = findnext(i, doc, findwhat);
    if (i != -1) {
        /* select the text from i through i + strlen(findwhat) */
        i += (int)strlen(findwhat);
    } else {
        i = 0; /* the next attempt starts at the beginning */
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents