strstr
/* 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
在 needle
(第一個)引數中搜尋 needle
指向的字串。如果找到,strstr
將返回事件的地址。如果找不到 needle
,則返回 NULL。我們使用 zbpos
,以便我們不會一遍又一遍地找到相同的針。為了跳過第一個例項,我們新增了 zbpos
的偏移量。記事本克隆可能會像這樣呼叫 findnext
,以實現其查詢下一個對話方塊:
/*
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" */
}