Friday 31 January 2014

Explain strchr() and strstr() function with example.

strchr() function-This function returns pointer to a position of the first occurence of specified character in the given string.
syntax
chp=strchr(string,ch)   
chp is the pointer,ch is the character to be find in the string

Write a program to find a character in the string using strchr() function.

#include<stdio.h>
#include<conio.h>
main()
{
char string[10],*chp,ch;
clrscr();
printf("Enter the string");
gets(string);
printf("\n Enter the character to be find in the string:");
ch=getchar();
chp=strchr(string,ch);
if(chp)
    {
    printf("\n Character %c is found in the string",ch);
    }
        else
    {
    printf(""\n Character %c is not found in the string",ch);
    }
}
Output
Enter the string:Hello Begginers
Enter the character to be find in the string:r
Character r is found in the string

strstr() function-This function finds the second string in the given string.
syntax
strstr(str
ing1,string2)

Write a program to find a character in the string using strchr() function.

#include<stdio.h>
#include<conio.h>
main()
{
char string1[10],string2[10],*chp;
clrscr();
printf("Enter the first string");
gets(string1);
printf("\n Enter the second string to be found in the first string:");
gets(string2);
chp=strtr(string1,string2);
if(chp)
    {
    printf("\n second string %s is found in the first string",string1);
    }
        else
    {
    printf(""\n second string %s is not found in the first string",string2);
    }
}
Output
Enter the first string:Hello Begginers
Enter the second string to be found in the first string:Hello
second string Hello is found in the first string

No comments:

Post a Comment