33

我正在编写一个程序来解析一些保存为文本文件的数据。我要做的是在大海捞针中找到每根针的位置。我已经可以读取文件并确定出现次数,但我也在寻找索引。

4

2 回答 2

45
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);
}

编辑 我误读了您的帖子,您说的是子字符串,我以为您的意思是您正在搜索字符串。如果您将文件读入字符串,这仍然有效。

于 2010-10-27T15:16:35.763 回答
6

我知道答案已被接受,但这也将起作用,并且您不必将文件加载到字符串中。

#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
    }
  }
}
于 2010-10-27T16:08:03.650 回答