2010-10-27 110 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 
    } 
    } 
} 
相关问题