Saturday, January 29, 2011

Finding sub-string in a string in c++

The main goal of this program is to find a sub string in an inputted string
for example you give an "input hello i am a good boy" , and gives sub-string hello, it will find hello in the string that whether its there or not



******************* Start of Program ************************

// Finding sub-string in a String

#include"iostream.h"
#include"conio.h"
#include"stdio.h"

void main()
{
clrscr();
char str1[20],str2[20];
cout<<"Enter Main String :: ";
gets(str1);
cout<<"Enter sub string :: ";
gets(str2);

int i=0,j=0;

/////////

int h=0;
while(str2[h]!='\0') // to get number of chracters in sub string
{
h++;
}
//h-=1;

/////////



//while(str2[i]!='\0')
//{
// j=i;
int g=0;
int count=0; // to store number of matches

int c=0;

int flag;


while(str1[g]!='\0')
{

if(count==h)
break;

else
{

if(str2[c]==str1[g])
{
if(count==0)
flag=g;
count++;
c++;
}

else if(count>0)
{
c=0;
count=0;
g=flag;
}

else
{
// c++;
}

}

g++;

}



if(count==h)
{
cout<<"\n\nSub String Matched";
}
else
cout<<"\n\nSub String was not found";

getch();
}

******************* END ************************