2010-12-02 11 views
3

在std :: string中,是否可以在不使用循環的情況下找到一組字符串中的第一個?在std :: string中,是否可以在不使用循環的情況下找到一組字符串中的第一個?

例如爲:

std::string str("aaa bbb ccc ddd eee fff ggg"); 
std::vector<std::string> vs; 
vs.push_back("ccc"); 
vs.push_back("fff"); 
size_t pos = 0 
pos = str.find(vs, pos);  //< pseudo code 

謝謝!

+0

這是什麼語言? – Gerhard 2010-12-02 10:47:06

+0

@Gerhard,它的C++ – 2010-12-02 10:48:36

+1

如果你不循環,別人會。技術答案是「否」。 – tenfour 2010-12-02 11:34:07

回答

4

您可以將字符串(使用stringstream)拆分爲一個向量,然後使用帶有四個迭代器的std::find_first_of

下面是一個完整的代碼示例

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

using namespace std; 

int main(void) 
{ 
    string str("aaa bbb ccc ddd eee fff ggg"); 
    vector<string> vs; 
    vs.push_back("ccc"); 
    vs.push_back("fff"); 
    vector<string> scheck; 

    istringstream instr(str); 
    copy(istream_iterator<string>(instr), 
     istream_iterator<string>(), 
     back_inserter(scheck)); 

    vector<string>::iterator it = find_first_of (scheck.begin(), scheck.end(), vs.begin(), vs.end()); 
    if (it != scheck.end()) 
    cout << "first match is: " << *it << endl; 

    return 0; 
} 
4

最簡單的解決辦法是使用正則表達式庫如Boost.Regex像這樣的東西:

"\\b(ccc|fff)\\b" 
2

它,除非你使用正則表達式是不是真的有可能。 Boost.Regex可能是你的朋友。

0

林不知道,但我認爲:

str.find()將返回一個迭代器(「指數」)來發現的第一個實例。

,但我想你應該有:

size_t pos1 = str.find(vs.begin() , 0); 
size_t pos2 = str.find(vs.end() , 0); 
// since you have only ccc and fff , ccc is on begin(), and fff on end() 

???但我不知道。

編輯:我不認爲你可以找到向量中的所有字符串的發生沒有循環, ,除非你做循環展開。

0

當你沒有環說,你的意思是沒有一個手寫循環,因爲算法在執行過程中使用循環。

正如你可以找到一個單獨的字符串,你可以做一些與vec.begin(),vec.end()str.find和可能有點boost :: bind。

不知道你想對所有這些發現做什麼。像這樣的東西:

std::vector<std::string::size_type> locations; 
locations.reserve(vec.size()); 
std::transform(vec.begin(), vec.end(), std::back_inserter(locations), boost::bind(&std::string::find, str, _1)); 

會爲您生成這些項目被發現的位置的向量。如果你想要更高級的東西,例如保持狀態,你可以編寫你自己的仿函數,但如果代碼真的變得複雜,我看不到避免循環的價值。

相關問題