【问题标题】:Find all substring's occurrences and locations查找所有子字符串的出现和位置
【发布时间】:2011-05-01 09:20:33
【问题描述】:

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

【问题讨论】:

  • 请提供更多详细信息。代码示例将非常有助于理解您要执行的操作。
  • 如果不是代码,则为小样本输入所需的输出

标签: c++ iostream stdio


【解决方案1】:
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);
}

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

【讨论】:

  • 文件不是很长。这应该很完美:)谢谢!
  • @Steve -- 如果他能够像我说的那样将 100GB 文件读入字符串,那么是的,它会起作用。
  • 有人注意到这个解决方案在运行时间方面效率很低吗?
【解决方案2】:

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

#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
    }
  }
}

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2015-12-23
    • 1970-01-01
    相关资源
    最近更新 更多