string - C: Help with Custom strpos() Function -


i have 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;            = 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 when search single character:

printf("strpos: %d\n", strpos("a", "laoo")); // result: "strpos: 1" 

but improperly longer string:

printf("strpos: %d\n", strpos("ao", "laoo")); // result: "strpos: -1" 

what problem?

bonus question: while loop broken multiple lines? accepted way this?

edit: strlen() is, naturally, custom function returns length of string. works properly.

each time go round loop next character haystack. if needle has 2 characters time have finished comparing needle substring of haystack beginning @ position 0, haystack pointer pointing @ position 2 (for 2 character needle).

this means skip comparing needle substring of haystack beginning @ position 1.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -