查找所有子字符串的出现和位置 [英] Find all a substring's occurrences and locations
问题描述
我正在编写一个程序来解析一些保存为文本文件的数据。我想要做的是找到每个针在一个干草堆的位置。
<$ p $我已经可以读取文件并确定发生的次数,但我还在寻找索引。 p> string str,sub; // str是要搜索的字符串,sub是要搜索的子字符串
vector< size_t>位置; //保存sub中出现的所有位置
size_t pos = str.find(sub,0);
while(pos!= string :: npos)
{
positions.push_back(pos);
pos = str.find(sub,pos + 1);
}
编辑 ,你说的子串,我假设你的意思是你在搜索一个字符串。如果您将文件读入字符串,此操作仍然有效。
I'm writing a program to parse some data saved as text files. What I am trying to do is find the location of every needle in a haystack. I already can read the file in and determine the number of occurrences, but I am looking to find the index also.
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);
}
Edit I misread your post, you said substring, and I assumed you meant you were searching a string. This will still work if you read the file into a string.
这篇关于查找所有子字符串的出现和位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!