2012-01-23 4 views
0

は私が」、今私は、文字列全体が、「andgrapes」と言うと、あまりにもそれを変更したい文字列の一部のためではないベクトルを探索あまりにたいと思い、これにC++での文字列ベクトル[リンゴ、Orangesandgrapes]を持っていますnograpes "と呼ばれる。ほんの一例。どのように特定の文字やフレーズの文字列ベクトルをチェックするには?

私はそれをより明確にできなかった回答にSubstring search interview question 申し訳ありません。

+0

だから、あなたがこれまでのところ、思い付くことができたどのようなコード私たちを見ます。 – unwind

+1

このイテレータを試してみてください:「andgrapes」が代わりに最後の列の中央に表示されますhttp://stackoverflow.com/questions/3497310/substring-search-interview-question – mkb

答えて

2

あなたはこのような何かを行うことができます。私はこのためにboost::replace_allを使用する

#include <iostream> 
#include <vector> 
#include <string> 
#include <algorithm> 
#include <iterator> 

using namespace std; 

int main() { 

    vector<string> v; 
    v.push_back("Apples"); 
    v.push_back("Applesandgrapes"); 
    for_each(v.begin(), v.end(), 
     [] (string& s) 
    { 
     size_t pos = s.find("andgrapes"); 
     if(string::npos != pos) 
     { 
      s.erase(pos); 
      s += "nograpes"; 
     } 
    }); 

     copy(v.begin(), v.end(), ostream_iterator<string>(cout)); 
     return 0; 

} 
+0

場合はどうすれば? 1つの文字列に2回表示される場合はどうなりますか? –

3

#include <iostream> 
#include <vector> 
#include <string>  
#include <boost/algorithm/string/replace.hpp> 

int main() 
{ 
    std::vector<std::string> v = { "Apples", "Orangesandgrapes" };  
    for (auto & s : v)  
    { 
     boost::replace_all(s, "andgrapes", "nograpes"); 
     std::cout << s << '\n'; 
    }   
} 
関連する問題