查找所有子字符串的出现和位置 [英] Find all a substring's occurrences and locations

查看:285
本文介绍了查找所有子字符串的出现和位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来解析一些保存为文本文件的数据。我想要做的是找到每个针在一个干草堆的位置。

解决方案

<$ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆