/*How to search a
sub string without using library function strstr.
How to use pointer/array to search substring in a string sentence.
How to use pointer/array to search substring in a string sentence.
C++/CPP/C program/code to search a word in a sentence without using inbuilt function strstr*/
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[50];
printf("Enter a
String:\n");
scanf("%s",&arr1);
char arr2[20];
printf("Enter a
String:\n");
scanf("%s",&arr2);
printf("Searching
for:%s\n",arr2);
int count1, count2;
count1=0; count2=0;
while(arr1[count1]!='\0')
count1++;
while(arr2[count2]!='\0')
count2++;
int i,j,flag;
for(i=0;i<count1-count2;i++)
{
for(j=i;j<i+count2;j++)
{
flag=1;
if(arr1[j]!=arr2[j-i])
{
flag=0;
break;
}
}
if (flag==1)
break;
}
if (flag==1)
printf("yes
found\n");
else
printf("Not
found\n");
return 0;
}/*
Enter a String:
zxcvbnaaaSONYdkjsdfklj
Enter a String:
SONY
Searching for:SONY
Example: Builtin function strstr to find a substring in a string:
ReplyDeletestrstr function searches first occurrence of the substring(here word for cpp) in main string(here sentence howtocpp.com) and returns the pointer to the first char.
#include
using namespace std;
#include
int main main()
{
char sentence[]="howtocpp.com";
char word[]="cpp";
char *ptr;
ptr=strstr(sentence, word);
cout<<"The Substring is :"<<ptr;
return 0;
}
//This will output into
//The Substring is:cpp