Write a C++ program to find a sub-string within a string. If found display its starting position.
Program Code:
#include<iostream>
using namespace std;
int main( )
{
int i, j, length = 0; // Variable to hold length of second string
char name1[30], name2[30];
cout<<"Enter your first string: ";
cin.getline(name1, 30);
cout<<endl;
cout<<"Enter second string: ";
cin.getline(name2, 30);
cout<<endl;
for(i = 0; name2[i] != '\0'; i++) //finding length of second string
{
length = length + 1;
}
for(i = 0, j = 0; name1[i] != '\0' && name2[j] != '\0'; i++)
{
if(name1[i] == name2[j])
{
j++;
}
else
{
j = 0;
}
}
if(j == length)
{
cout<<"Sub-string ( Second String) is found at position "<< i - j + 1;
}
else
{
cout<<"Sub-string ( Second String) is not found";
}
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Enter your first string: mukesh
Enter second string: esh
Sub-string ( Second String) found at position 4
Thanks
Mukesh Rajput
Post A Comment:
0 comments: