2010-10-27 87 views
14

我正在編寫一個程序來解析保存爲文本文件的一些數據。我想要做的是在乾草堆中找到每根針的位置。我已經可以讀入文件並確定出現的次數,但我正在尋找索引。查找所有子字符串的出現次數和位置

+1

更多詳情請。代碼示例對理解你想要做的事很有幫助。 – 2010-10-27 15:13:17

+0

如果不是代碼,那麼對於小樣本輸入需要輸出 – 2010-10-27 15:16:29

回答

18
string str,sub; // str is string to search, sub is the substring to search for 

vector<size_t> positions; // holds all the positions that sub occurs within str 

size_t pos = str.find(sub, 0); 
while(pos != string::npos) 
{ 
    positions.push_back(pos); 
    pos = str.find(sub,pos+1); 
} 

編輯 我誤解你的帖子,你說子,我假設你的意思是你正在尋找一個字符串。如果您將該文件讀入字符串,這仍然可以工作。

+0

=如果文件長度爲100GB會怎麼樣?這仍然有效嗎? – 2010-10-27 15:25:48

+0

該文件不是很長。這應該完美:)謝謝! – 2010-10-27 15:27:26

+0

@Steve - 如果他能夠像我說的那樣將100GB文件讀入字符串,那麼是的,它會起作用。 – 2010-10-27 15:27:29

4

我知道答案已被接受,而且這也將工作,將節省您具有該文件到一個字符串中加載..

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <algorithm> 

using namespace std; 

int main(void) 
{ 
    const char foo[] = "foo"; 
    const size_t s_len = sizeof(foo) - 1; // ignore \0 
    char block[s_len] = {0}; 

    ifstream f_in(<some file>); 

    vector<size_t> f_pos; 

    while(f_in.good()) 
    { 
    fill(block, block + s_len, 0); // pedantic I guess.. 
    size_t cpos = f_in.tellg(); 
    // Get block by block.. 
    f_in.read(block, s_len); 
    if (equal(block, block + s_len, foo)) 
    { 
     f_pos.push_back(cpos); 
    } 
    else 
    { 
     f_in.seekg(cpos + 1); // rewind 
    } 
    } 
} 
相關問題