strpos in C- how does it work

The function you are looking for might be either strstr or strchr. You then need to include string.h. There is no strpos in the POSIX interface.


Here a complete snippet code to solve you problem. PS: Isn't too late to help. ;)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NOT_FOUND -1

int main (){
    int pos = NOT_FOUND;
    if ( (pos = strpos( "subsstring", "string")) != NOT_FOUND )
        printf("found at %d\n", pos);
    else
        printf("not found!\n");
    return 0;
}

int strpos(const char *haystack, const char *needle)
{
   const char *p = strstr(haystack, needle);
   if (p)
      return p - haystack;
   return NOT_FOUND;
}

Edit: Answering Can Vural question:

No. I really think that it would be as it is. At structured programming paradigm, it's a common practice to use the scope structure as first parameter on every function that belongs to the structure's scope itself. The strstr function defined at string.h follow the same approach.

On OOP you have haystack.indexOf( needle ). At structured programming, you have indexOf( haystack, needle ).


Yes. It's called strstr, related to strpos like (pseudo-code):

strpos(str, target) {
   res = strstr(str, target); 
   if (res == NULL) return false;
   else             return res - str;
}

I have written strpos() function from scratch with position feature(Like PHP's strpos() function). Return value will be starting position of searched string. Enjoy! :)

In this example code output will be 12

#include <stdio.h>
#include <string.h>

int strpos(char *haystack, char *needle, int pos);

int main(){

    printf("%d",strpos("abcdefabcdefabcdef asdfgavcabcddd","abc",10));

    return 0;
}

int strpos(char *haystack, char *needle, int pos){
    int i,j,check,result = -1;
    int len_needle=strlen(needle);
    int len_haystack=strlen(haystack);  
    i = pos;
    if (len_needle>len_haystack || *needle==NULL || i>(len_haystack-1)) return result;

    for(;i<len_haystack;i++){
        check = 0;
        for(j=0;j<len_needle;j++){
            if(haystack[i+j]==needle[j]){
                check++;
            }
        }           
        if(check==len_needle){
            result = i;
            break;
        }

    }
    return result;
}

Tags:

C