【发布时间】:2011-05-01 09:20:33
【问题描述】:
我正在编写一个程序来解析一些保存为文本文件的数据。我想做的是在大海捞针中找到每根针的位置。我已经可以读取文件并确定出现的次数,但我也在寻找索引。
【问题讨论】:
-
请提供更多详细信息。代码示例将非常有助于理解您要执行的操作。
-
如果不是代码,则为小样本输入所需的输出
我正在编写一个程序来解析一些保存为文本文件的数据。我想做的是在大海捞针中找到每根针的位置。我已经可以读取文件并确定出现的次数,但我也在寻找索引。
【问题讨论】:
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);
}
编辑 我误读了您的帖子,您说的是子字符串,我以为您的意思是您正在搜索字符串。如果您将文件读入字符串,这仍然有效。
【讨论】:
我知道答案已被接受,但这也可以,并且您不必将文件加载到字符串中。..
#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
}
}
}
【讨论】: