Sunday, September 8, 2013

[C++] Searching a word in a sentence

[C++] Searching a word in a sentence 

#include <iostream>
#include <string>
using namespace std;

int main(){

   int found=0;
   int flag=0;

   string s1;
   cout<<"Enter the text: ";
   getline(cin,s1);
   string s2;
   cout<<"\nEnter term to search: ";
   getline(cin,s2);
   cout<<endl;

   int lengthLine = s1.size();
   const int lengthTerm = s2.size();

   string s3;
   s3.resize(lengthTerm);
   
  int g = 0;

   for(int i = 0; i<lengthLine; i++, g++)
   {
 
  if(g<lengthTerm)
  {
  s3[g]=s1[i];       
  }
  
  if(g>=lengthTerm)   
  {
  for(int z=0;z<lengthTerm-1;z++)
  {
  s3[z]=s3[z+1];    
  }
  
  s3[lengthTerm-1]=s1[i];  
  }
 if(s3==s2)
  {
  ++found;
  }
   }

   cout<<"\n\nTerm found "<<found<<" time(s).\n\n";
}

No comments:

Post a Comment