2014-04-14 23 views
1

我想使用函數搜索或其他類似的函數來查找給定模式的多次出現。使用std :: search來查找多個出現的模式

這是我的代碼:

#include <cstring> 
#include <iostream> 
#include <iomanip> 
#include <set> 
#include <list> 
#include <vector> 
#include <map> 
#include <algorithm> 
#include <functional> 
using namespace std; 

int main() { 
    std::vector<int> haystack; 

    string a = "abcabcabc"; 
    string b = "abc"; 
    string::iterator it; 
    it = search(a.begin(),a.end(),b.begin(),b.end()); 

    if(it!=a.end()){ 
     cout << it-a.begin()<<endl; 
    } 

    return 0; 
} 

此代碼模式「ABC」的第一次出現返回0,想返回0,3,6,這將是所有指標的原模式開始的字符串。

謝謝你的幫助。

+2

的[找到所有的子串的事件和地點]可能重複(http://stackoverflow.com/questions/4034750/find-all-a-substrings-occurrences-and-locations ) – CoryKramer

+0

你需要一個循環,它應該在'it == a.end()'時完成。你嘗試了什麼?有什麼特別的原因,你沒有使用'a.find'? – Useless

回答

3
for(size_t pos=a.find(b,0); pos!=std::string::npos; pos=a.find(b,pos+1)) { 
    std::cout << pos << std::endl; 
}  

這使用std::basic_string::findref)直接找到的子串的起始位置。

+0

這段代碼是否從開始到結束每次搜索?還是從最後的位置繼續? –

+0

它從'pos + 1'繼續。 – Danvil

+0

如果要進行不區分大小寫的搜索,該怎麼辦?在這種情況下,find()將不起作用。我不知道如何推進搜索()中的迭代器。有任何想法嗎? – user2761431

1

search函數搜索第一個字符串a以查找第二個字符串b的元素髮生的任何情況。至於你的第二個字符串中包含的元素abc代碼將返回一個迭代到第一位置,然後到第二個,第三個......

什麼,你用什麼find功能。它將一個迭代器返回到與您正在搜索的元素相同的元素。在您的情況下,您正在搜索元素abc的字符串a。所以,你將不得不調用

string::iterator it = std::find(a.begin(), a.end(), "abc"); 
while (it != a.end()) { 
    // Do whatever you want to do... 
    ++it; 
    it = std::find(it, a.end(), "abc"); 
} 
+0

我可以至少知道downvote的原因嗎? – sleepy42

相關問題