Program to find sub string in a string

Program to find sub string in a string

Question:

Write a c program to find a sub string in a string.

Logic:

  • Get the input string and string to search from the user.
  • Find the length of both string for searching.
  •  Checks the sub string in the main string.
  •  Print the position if string is found otherwise print not found.

Algorithm:

  1. Get the input string and string to search from the user.
  2.  Find both strings length using strlen() function.
  3.  If the first element of the searching string is matching.
  4.  Then checks with other elements by incrementing position.
  5.  If search string length and incremented value is equal means string is found.
  6.  Otherwise string is not found.

Program:

#include<stdio.h>
void main()
{
	char a[30],b[20];
	int n,i,j,m,c=0;
	clrscr();
	printf("enter the string:");
	gets(a);
	printf("enter the string to search:");
	gets(b);
	//find both strings length and store it in variable
	n=strlen(a);
	m=strlen(b);
	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
		{
			if(a[i]==b[j])//checks all the elements in string
			{
				i++;
				c++;
			}
			if(c==m)//if both the length of string to search and value of c
			{
				printf("string found at position %d,%d",i-m,i-1);
				break;
			}
		}
		if(c==m)//exits from outer loop when string found
		{
			break;
		}
		i=i-c;c=0;
	}
	if(c==0)//if string not found
	{
		printf("not found");
	}
	getch();
}

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.
0 0 votes
Article Rating
Subscribe
Notify of
guest
5.4K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
5.4K
0
Would love your thoughts, please comment.x
()
x