C++ Program to Find Substring from String

Write C++ Program to Find Substring from String

// CPP Program to Find Substring from String

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main()
{
	char S1[50], S2[15];
	int index, i, l1, l2, j, Max;

	cout << "Enter String :--> ";
	gets(S1);

	cout << "Enter Substring :--> ";
	gets(S2);

	l1 = strlen(S1);
	l2 = strlen(S2);
	Max = l1 - l2;

	for(i = 0;i <= Max; i++)
	{
		if(strncmp(S1 + i, S2, l2) == 0)
            /* here a and b is considered as array address and
            a+i means array is compared with array b
            upto the size of substring */
			break;
	}
	if(i <= Max)
		cout << "\nSubstring is located at index --> " << i;
	else
		cout << "\nSubstring not found";

	return 0;
}

Output:

Run 1:
Enter String :--> Hello CodeCrucks
Enter Substring :--> Code

Substring is located at index --> 6

Run 2:
Enter String :--> Hello CodeCrucks
Enter Substring :--> Python

Substring not found

≪ Previous | Next ≫