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:
- Get the input string and string to search from the user.
- Find both strings length using strlen() function.
- If the first element of the searching string is matching.
- Then checks with other elements by incrementing position.
- If search string length and incremented value is equal means string is found.
- 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(); }