2010-04-12 38 views
1

我有一個很長的字符串變量,我想根據這些字搜索特定的單詞和限制文本。如何檢查標準字符串內的位置是否存在? (C++)

說我有以下文字:

這個驚人的新的可佩戴的音頻解決方案採用嵌入到襯衫前面的工作揚聲器,可以播放音樂或適用於任何情況的音效這就像主演在你自己的電影裏

和詞:」解決方案「,」電影「。

我想從(在搜索結果頁像谷歌)的大字符串。減去:

「......新的可佩戴的音頻解決方案特色 ...嵌入工作揚聲器」 和 」 ...就像在你自己的電影

主演,我正在使用的代碼:

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+="...";  
     }  
     } 

但desc.at(LOC 1-i)會導致OutOfRange異常......我不知道如何檢查該位置是否存在,而不會導致異常!

請幫忙!

+3

什麼是瘋狂的縮進級別?請讓您的代碼更易於閱讀,這樣人們就不必如此努力工作來幫助您。 – 2010-04-12 04:18:54

+0

你的意思是你想從文本中刪除任何給定的字符串? – wilhelmtell 2010-04-12 04:19:55

+0

哦,對不起,我花了時間在格式化,但apparrently現在還不清楚..我的工作就可以了對不起;) – Youssef 2010-04-12 04:20:43

回答

1

這是採取什麼樣的STL所提供優勢的極好的鍛鍊。您只需打開一個reference和櫻桃選擇算法和類爲您的解決方案!

#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; 
} 
1

你可以只檢查desc.size() - 如果它是用不到索引你仰視+ 1那麼你會得到一個異常

0

的問題是,你開始在第一個字迭代,然後嘗試檢查它之前的單詞,因此是OutOfRange異常。

你的第一個,如果可能是:

if(loc1 != string::npos && loc1 != 0) 
相關問題