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 = 0;
            foundPos = -1;


    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.


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.

Need Your Help

Problem in Flash TextField

flex flash actionscript-3 flash-cs4

I want to design a calculator by Flash cs5 , I use appendText Method to write the data in the textfield by the Keyboard . My problem is when I start the application I have to Click on the TextField

Retrieve div id value using ExtJS

javascript dom extjs

Ok this might be an easy question but I think I am missing something obvious. In my Sencha/ExtJS app I am trying to retrieve an ID value from a div as it is randomized, auto-generated by ExtJS. S...