i have a long string variable and i want to search in it for specific words and limit text accordin开发者_运维百科g to thoses words.
Say i have the following text :
"This amazing new wearable audio solution features a working speaker embedded into the front of the shirt and can play music or sound effects appropriate for any situation. It's just like starring in your own movie"
and the words : "solution" , "movie".
I want to substract from the big string (like google in results page):
"...new wearable audio solution features a working speaker embedded..." and "...just like starring in your own movie"
for that i'm using the code :
for (std::vector<string>::iterator it = words.begin(); it != words.end(); ++it)
{
int loc1 = (int)desc.find( *it, 0 );
if( loc1 != string::npos )
{
while(desc.at(loc1-i) && i<=80)
{
i++;
from=loc1-i;
if(i==80) fromdots=true;
}
i=0;
while(desc.at(loc1+(int)(*it).size()+i) && i<=80)
{
i++;
to=loc1+(int)(*it).size()+i;
if(i==80) todots=true;
}
for(int i=from;i<=to;i++)
{
if(fromdots) mini+="...";
mini+=desc.at(i);
if(todots) mini+="...";
}
}
but desc.at(loc1-i) causes OutOfRange exception... I don't know how to check if that position exists without causing an exception !
Help please!
This is an excellent exercise in taking advantage of what the STL has to offer. You simply open a reference and cherry-pick algorithms and classes for your solution!
#include <iostream> // algorithm,string,list,cctype,functional,boost/assign.hpp
using namespace std;
struct remove_from {
remove_from(string& text) : text(text) { }
void operator()(const string& str) {
typedef string::iterator striter;
striter e(search(text.begin(), text.end(), str.begin(), str.end()));
while( e != text.end() ) {
striter b = e;
advance(e, str.length());
e = find_if(e, text.end(), not1(ptr_fun<int,int>(isspace)));
text.erase(b, e);
e = search(text.begin(), text.end(), str.begin(), str.end());
}
}
private:
string& text;
};
int main(int argc, char* argv[])
{
list<string> toremove = boost::assign::list_of("solution")("movie");
string text("This amazing new wearable ...");
for_each(toremove.begin(), toremove.end(), remove_from(text));
cout << text << endl;
return 0;
}
You can just check desc.size() - if it's less than the index you're looking up + 1 then you'll get an exception
The problem is that you start iterating at the first word, then try and check the word before it, hence the OutOfRange Exception.
Your first if could be:
if( loc1 != string::npos && loc1 != 0)
精彩评论