2012-01-23 2 views
0

나는이 [사과, Orangesandgrapes]와 함께 C++에서 문자열 벡터를 가지고 있습니다. 이제는 전체 문자열이 아니라 "andgrapes"라는 문자열의 일부도 벡터를 검색하고 싶습니다. 또한이를 변경하려고합니다. " nograpes ". 모두 한 모범입니다.특정 문자 또는 문구의 문자열 벡터를 확인하는 방법은 무엇입니까?

Answer Substring search interview question 죄송합니다. 명확히 할 수 없습니다.

+0

그래서, 당신은 지금까지 마련하기 위해 관리했습니다 어떤 코드를 우리에게 보여줍니다. – unwind

+1

다음과 iterator를 사용해보십시오 : 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

"andgrapes"가 문자열 대신에 문자열의 중간에 나타나면 어떻게 될까요? 한 문자열에 두 번 나타나는 경우 어떻게해야합니까? –

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'; 
    }   
} 
관련 문제