Find the location of given sub string in a String

Description

Get a String and Substring and find where the substring is present in String.
Input:
entertainment
ain
Ouput:
6

Solution

#include<stdio.h>
#include<string.h>
int main()
{
	char str[50],s[30];
	int i,j,k,b;
	fgets(str,50,stdin);
	fgets(s,50,stdin);
	for(i=0;i<=strlen(str)-strlen(s);i++)
	{
		j=0;
		b=0;

		if(str[i]==s[j])
		{
			for(k=i;j<=strlen(s)-1;k++,j++)
			{
				if(str[k]!=s[j])
				{	
					b=1;	
					break;
				}
			}
			if(b==0)
			{
				printf("Sub string is at %d",i);
				return 0;
			}
		}
	}
	printf("sub String not found");
	return 0;
}

	

Explanation

check whether first character of sub string is equal to any character in string. If it is equal, then check remaining characters are equal to the characters in substring.  else move to next character.
Ramesh P Natarajan

Author - Ramesh P Natarajan

Learner, Professor, Technology Trainer, Software Developer and Content Marketer, very much passionate in the field of Software Application Development, Machine Learning and Search Engine Optimization.

Write to: [email protected]





Interesting Pattern Programs: for more Patterns

Input:
5
Output:
*
**
***
****
*****
****
***
**
*Solution
Input:
5
Output:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *Solution
Input:
5
Output:
*        *
**      **
***    ***
****  ****
**********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********
**** ****
***   ***
**     **
*       *Solution
Input:
5
Output:
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********Solution