04-04-2015, 12:13 AM
(03-13-2015, 05:34 PM)greatgamer34 Wrote: 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;
}
How about
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;
string mark(string text,int startPos, int len){
string toReturn = text;
toReturn.insert(startPos,"***");
toReturn.insert(startPos+len+3,"***");
return toReturn;
}
int main(void){
cout<<"~~~~~~~~~~~~~~"<< endl
<<"Keyword Finder"<< endl
<<"~~~~~~~~~~~~~~"<< endl;
//Get user preferences
string keyword = "ban";
int lenKeyword;
lenKeyword = keyword.size();
string keywordPadded = " "+keyword+" ";
//Read in data
string fullText = "ban bananas, they are bannable when ban bands ban the bans ban";
cout<<"File Text: "<< fullText << endl;
cout<<fullText.size()<<endl;
//iterate through each potential match and mark it
for(int i = fullText.find(keywordPadded); i < fullText.size(); i = fullText.find(keywordPadded,i+lenKeyword)){
cout << i << endl;
fullText = mark(fullText,i+1,lenKeyword);
}
//check edge cases
if(fullText.find(keyword+" ")==0)
fullText = mark(fullText,0,lenKeyword);
if(fullText.find(" "+keyword,fullText.size()-lenKeyword-1)==fullText.size()-lenKeyword-1)
fullText = mark(fullText,fullText.size()-lenKeyword,lenKeyword);
cout<<"Highlighted Text: "<< fullText << endl;
return 0;
}
(Didn't fuck around with file I/O because I was using an online compiler, should be simple to implement though)