C: Help with Custom strpos() Function
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")); // Resu开发者_如何学Pythonlt: "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.
Each time you go round the loop you get the next character from haystack. So if needle has two characters by the time you have finished comparing needle with the substring of haystack beginning at position 0, the haystack pointer is pointing at position 2 (for a two character needle).
This means that you skip comparing needle with the substring of haystack beginning at position 1.
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.
if(temp == *needle+nePos)
Should be:
if(temp == *(needle+nePos))
精彩评论