Sunday, September 6, 2009

C skills : tutor 5: StrStr Library function





char *strstr(char *string1, char *string2);


Description:

The strstr function locates the first occurrence of the string string2 in the string string1 and returns a pointer to the beginning of the first occurrence.

Return Value

The strstr function returns a pointer within string1 that points to a string identical to string2. If no such sub string exists in src a null pointer is returned.



/* user defined strstr */

#include "stdio.h"


char * strstr_ud(char *, char *);

int main()
{

char s1 [] = "This House is Nice";
char s2 [] = "My Car is White";

printf("Returned String 1: %s\n", strstr_ud(s1, "House"));
printf("Returned String 2: %s\n", strstr_ud(s2, "Car"));
return 0;

}

char * strstr_ud(char * str1, char * str2)
{

char *temp1=NULL;
char *temp2=NULL;

temp2 = str2;
while(*str1++ != '\0')
{

if(*str2 == *str1)
{
temp1 = str1;

while(*str2 != '\0')
{
if(*str2 != *temp1)
{
flag = 1;
}
else
{
flag = 0;
}
str2++;temp1++;
}

if(flag == 0)
{
return str1;
}
else
{
str2 = temp2;
}

}

}

return NULL;

}


Output
House is Nice
Car is White

No comments:

Post a Comment