I have the following function:
int strpos(const char *needle, const char *haystack)
{
int neLen, haLen, foundPos, nePos, i;
char temp;
neLen = strlen(needle);
haLen = strlen(haystack);
if(haLen < neLen)
return -1;
nePos = 0;
foundPos = -1;
i = 0;
while((temp = *haystack++) != '\0'
&& (i < (haLen-neLen+1) || foundPos > -1)
&& nePos < neLen)
{
if(temp == *needle+nePos)
{
if(nePos == 0)
foundPos = i;
nePos++;
}
else
{
nePos = 0;
foundPos = -1;
}
i++;
}
return foundPos;
}
It works properly when I search for a single character:
printf("Strpos: %d\n", strpos("a", "laoo")); // Result: "Strpos: 1"
But it improperly with longer string:
printf("Strpos: %d\n", strpos("ao", "laoo")); // Result: "Strpos: -1"
What is the problem?
Bonus question: is the while loop properly broken into multiple lines? What is the accepted way to do this?
EDIT: strlen() is, naturally, a custom function that returns the length of the string. This works properly.
The solution is of the standard bang-your-head-against-the-wall-in-an-infinite-loop-and-wonder-why-the-hell-you’re-a-programmer variety.
Should be: