Here is the code:
int position(char *s1, char *s2) {
int i, j;
for (i = 0; s1[i]; i++) {
for (j = 0; s2[j] && s2[j] == s1[i + j]; j++);
if (!s2[j]) return i;
}
return -1;
}
int main() {
char word1[101], word2[101];
int p;
printf("Type two words: ");
scanf("%s %s", word1, word2);
p = position(word1, word2);
if (p < 0)
printf("Word'%s' does not exists in the sentence '%s'.", word2, word1);
else
printf("Position of the word '%s' is %d.", word2, p);
return 0;
}
How does the second for loop work?
Does the function return i if it detects the word, if so how?
The loop
for (j = 0; s2[j] && s2[j] == s1[i + j]; j++);has an empty body;which can also be written:or
It computes the length of the initial substring of
s2that matches characters at offsetsiand subsequent ofs1. At the end of the loop,jis the number of matching characters up to but not including the null terminator.It this initial substring is the full string
s2, which can be tested by comparings2[j]to the null terminator'\0', we have a match at positioni, henceif (!s2[j]) return i;Note that this function returns
0for an empty substrings2, except ifs1is also empty, which is somewhat inconsistent. It should either return0in all cases:Note also that this function may have undefined behavior if
s1is longer thanINT_MAX, which is possible on 64-bit systems whereinthas 32 bits and pointers and object sizes have 64 bits. It would be safer to change theintvariable and return types toptrdiff_tdefined in<stddef.h>, albeit not full sufficient.The standard function
strstrdoes not have these shortcomings as it is defined as returning a pointer to the match:Note however that in C, it returns a non
constpointer even if passed aconstpointer, potentially breakingconstcorrectness.Here is a simplistic implementation using the same algorithm:
Good C libraries use more sophisticated algorithms, which I encourage you to search and study.