テキストファイルとして保存されたデータを解析するプログラムを書いています。私がやろうとしているのは、干し草の山にあるすべての針の位置を見つけることです. 私はすでにファイルを読み込んで出現回数を判断できますが、インデックスも探しています。
質問する
42843 次
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 に答える