03-13-2015, 05:34 PM
Hey guys, i've devised a cool way to search for a keyword in a string in C++. Just compile and run.
PHP Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
int main(void)
{
int a,i,z,loc,pos;
string inputFileName;
string s,term;
ifstream fileIn;
char ch;
cout<<endl;
cout<<endl;
cout<<"Enter the name of a file of characters: ";
cin>>inputFileName;
cout<<endl;
cout<<endl;
fileIn.open(inputFileName.data());
assert(fileIn.is_open() );
i=0;
while (!(fileIn.eof()))
{ch=fileIn.get();
s.insert(i,1,ch); //insert character at position i
i++;
}
cout<<s;
cout<<endl;
cout<<endl;
cout<<"Enter a word/phrase you want to search for in the file you entered: ";
cin>>term;
cout<<"The word/phrase *"<< term <<"* will have '***' before it and after it"<<endl;
cout<<endl;
z = (int)term.length();
loc = 0;
while ((loc = s.find(term, loc)) != std::string::npos)
{
// check for space at start of term, or check
// for beginning of string
if (loc != 0 && s[loc - 1] != ' ')
{
loc += z;
continue;
}
// check for space at end of term, or check for end of string
if (loc != (s.length() - z) && s[loc + z] != ' ')
{
loc += z;
continue;
}
s.insert(loc, 1, '*');
s.insert(loc+1, 1, '*');
s.insert(loc+2, 1, '*');
s.insert(loc+3+z, 1, '*');
s.insert(loc+4+z, 1, '*');
s.insert(loc+5+z, 1, '*');
loc += z;
loc += 6; // the amount of asterisks added
}
cout<<s;
return 0;
}