C++ program to find the substring in a given string

Program:

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char str1[100],test[100];
    cout<<"Enter the string :\n";
    cin>>str1;
    cout<<"Enter the substring: \n";
    cin>>test;
    int l=strlen(test);
    int i,j;
    for(i=0;str1[i]!='\0'&&test[j]!=0;i++)
    {
        if(str1[i]==test[j])
        {
            j++;
        }
        else
        {
            j=0;
        }
    }
    if(j==l)
    {
        cout<<"substring is found at position "<<i-j+1;
    }
    else
    {
        cout<<"substring is not found ";
    }
    
}

output:

Enter the string :                                                                                                                             
imaginedragons                                                                                                                                 
Enter the substring:                                                                                                                           
dagon                                                                                                                                          
substring is not found     

Enter the string :                                                                                                                             
helloworld                                                                                                                                     
Enter the substring:                                                                                                                           
orld                                                                                                                                           
substring is found at position 7  

Comments

Popular posts from this blog

C program to print the following Pattern

For any given matrix find the path from the start to the end which gives the maximum sum. Traverse only right or down. Example: starting index is 15 (left top) and ending index is 10 (bottom right) 15 25 30 45 25 60 70 75 10 O/P:15->45->70->75->10 sum is 215

c++ program to print string along the diagonals of the matrix.