Assignments » String » Set1 »Solution 7

solution of question 7
[SET – 1]

Write a program to find a substring within a string. If found display its starting position.


#include<iostream.h>
#include<conio.h>
#include<stdio.h>

int main( )
{
	clrscr( );

	char str1[80],str2[80];
	cout<<"Enter first string :";
	gets(str1);
	cout<<"Enter second string :";
	gets(str2);

	for(int l=0;str2[l]!='\0';l++);    //finding length of string 2

	for(int i=0,j=0;str1[i]!='\0'&& str2[j]!='\0';i++)
		if(str1[i]==str2[j])
			j++;
		else
			j=0;

	if(j==l)
		cout<<"Substring found at position "<<i-j+1;
	else
		cout<<"Substring not found";
	
	getch();
	return 0;
}

 

 

«back