Skip to main content

Pattern Searching

Task : Find the pattern from the text. If the pattern is present print found else print not found.

Example:
Input: 
2
hellofriends
hello
asdfghjkl
ask
Output:
found
not found

Here is the Code :

Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int main()
  5.  {
  6. int t;
  7. cin>>t;
  8. while(t--)
  9. {
  10.     string s1,s2;
  11.     cin>>s1;
  12.     cin>>s2;
  13.     int n=s1.length(),m=s2.length();
  14.     // Implementation of logic
  15.     if(n<m)
  16.     {
  17.         cout<<"not found"<<endl;
  18.     }
  19.     else
  20.     {
  21.         int c = 0;
  22.         for(int i=0;i<=n-m;i++)
  23.         {
  24.             string t = s1.substr(i,m);
  25.             if(t == s2)
  26.             {
  27.                 cout<<"found"<<endl;
  28.                 c=1;
  29.                 break;
  30.             }
  31.         }
  32.         if(c==0) cout<<"not found"<<endl;
  33.     }
  34. }
  35. return 0;
  36. }

Here is the Video: