Strstr if all characters in pattern are different

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


int Strstr(const char *str, const char *pattern)
{
/*Null pointers or null strings return 0*/
if(!str || !*str || !pattern || !*pattern)
return 0;

/*Compare lengths*/
size_t patlen = strlen(pattern);
size_t len = strlen(str);

if(patlen > len)
return 0;

else if(patlen == len)
return strcmp(str, pattern) == 0;

/*find the position of the first character of the pattern*/
if((str = strchr(str, *pattern)) == NULL)
return 0;

const char *p;


/*find next position of first character of the pattern*/
while(p = strchr(str + 1, *pattern))
{
if((p - str) >= patlen) /*As all characters in the pattern are distinct*/
{
if(strncmp(str, pattern, patlen) == 0)
return 1;
}

str = p;
}

return strncmp(str, pattern, patlen) == 0;
}

int main()
{
char str[64], pat[64];

scanf("%s", str);

scanf("%s", pat);

printf("%d\n", Strstr(str, pat));

return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s