Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strpos in C- how does it work

Tags:

c

I am really new to C.

I want to use the strpos function but it is telling me it doesnt exist?

like image 250
SuperString Avatar asked Jan 19 '10 07:01

SuperString


2 Answers

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(char *haystack, char *needle)
{
   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 ).

like image 147
Miere Avatar answered Sep 20 '22 14:09

Miere


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.

like image 42
user231967 Avatar answered Sep 19 '22 14:09

user231967