When searching a line for an occurrence of a word, you need a pointer to advance over each character in the line, a search term, comparison of the current character with the first character in search term, further comparison if there is a match, and then a set of delimiters to limit the comparisons as required to, for example, if searching for 'the'
only match 'the'
and not 'they'
, 'them'
, 'then'
, 'there'
, etc...
You can use basic arithmetic to your advantage to insure you don't attempt to check lines shorter then the search term length, etc.. A short example (changing the initial 'The'
to 'the'
in your line for example purposes), you can do something similar to the following. Note, there are only basic optimization used int the search and it isn't intended to be an exhaustive example:
#include <stdio.h>
#include <string.h>
int main (int argc, char **argv)
{
char line[] = "the quick brown fox jumps over the lazy dog.";
char *p = line;
char *sterm = argc > 1 ? argv[1] : "the";
char *delim = " \t\n\'\".";
size_t llen = strlen (line);
size_t count = 0, slen = strlen (sterm);
printf ("\n searching line for '%s'\n\n", sterm);
for (;p < (line + llen - slen + 1); p++) {
if (*p != *sterm)
continue; /* char != first char in sterm */
if (p > line && !strchr (delim, *(p - 1)))
continue; /* prior char is not a delim */
if (!strchr (delim, *(p + slen)))
continue; /* next char is not a delim */
if (strncmp (p, sterm, slen))
continue; /* chars don't match sterm */
printf (" match %2zu. '%s' at location %zu\n",
++count, sterm, p - line);
}
printf ("\n total occurrences of '%s' in line : %zu\n\n",
sterm, count);
return 0;
}
Use/Output
$ ./bin/searchline
searching line for 'the'
match 1. 'the' at location 0
match 2. 'the' at location 31
total occurrences of 'the' in line : 2
$ ./bin/searchline fox
searching line for 'fox'
match 1. 'fox' at location 16
total occurrences of 'fox' in line : 1
Note the use of strchr
with the delimiter string delim
using the current character as the char
. Look over the example and let me know if you have any questions. Your exact goal was a bit unclear from your question, so if I missed your intent, let me know.
Using Array Indexes Instead of Pointer
If you are more comfortable using character array indexes instead of pointers, you can always remove the pointer p
and adjust the loop logic accordingly:
for (i = 0; i < (llen - slen + 1); i++) {
if (line[i] != *sterm)
continue; /* char != first char in sterm */
if (i && !strchr (delim, line[i-1]))
continue; /* prior char is not a delim */
if (!strchr (delim, line[i+slen]))
continue; /* next char is not a delim */
if (strncmp (&line[i], sterm, slen))
continue; /* chars don't match sterm */
printf (" match %2zu. '%s' at location %zu\n",
++count, sterm, &line[i] - line);
}