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

Source Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
using namespace std;

int main( )
{
    char str1[80], str2[80];
 
    cout<<"Enter first string: ";
    cin.getline(str1, 80);
 
    cout<<"Enter second string: ";
    cin.getline(str2, 80);

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

    int i, j;
    
    for(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";
 
    return 0;
}

Post a Comment

 
Top