c programming strstr string.h

In C programming the <string.h> strstr function searches for the first occurrence of a string in another string.More detail explanation is given below.The declaration of the function is given below.

char *strstr(const char *s1 , const char *s2);

s1 -The first string.

s2 -The second string.This string is occurrence is search in ‘s1’ excluding the null-terminated value.

Return type
char* -Returns a pointer to the located string, or a null pointer if the string is not found.If ‘s2’ points to a string with zero length,the function returns ‘s1’.

Note the whole string of ‘s2’ must match the sequence in ‘s1’ only if part of the sequence of character of ‘s2’ match in ‘s1’ then the function will always return null.

Code example

char s1[]=”Happy place” , s2[]=”place” , s3[]=”pla” , s4[]=”pla now” , s5[]=”” , *ret;

ret = strstr(s1 , s2);

printf(“ret=%s” , ret);

ret = strstr(s1 , s3);

printf(“\nret=%s” , ret);

ret = strstr(s1 , s4);

printf(“\nret=%s” , ret);

ret = strstr(s1, s5);

printf(“\nret=%s”, ret);


ret=Happy place

The first ‘strstr’ call, ‘s2’ string match the second string in ‘s1’ so the pointer to that string(“place”) is returned.

In the second ‘strstr’ call,the string ‘s3’ match partly with the second string of ‘s1’,hence the pointer t the second string “place” is returned.

In the third ‘strstr’ call,only the first sequence ‘pla’ of s4 match partly with the second character sequence of s1,but the function requires that the the whole string of s4 should match and which isn’t the case so here null is returned.

In the fourth ‘strstr’ call the string s5 has 0 length so the pointer to ‘s1’ string is returned.

Related links

->C strcspn string.h

->C strpbrk string.h

->C strrchr string.h

->C strchr string.h

->C strspn string.h

->C strtok string.h