如何在c++中找到字符串中子字符串的出现次数和位置
How to find number of occurence and position of a substring in a string in C++
我正在努力寻找字符串中子字符串的位置数量。下面的代码只提供了字符串中子字符串的起始位置。请帮帮我。
void Search(std::string SubString, vector<string> index)
{
vector<string>::const_iterator cii;
string temp;
bool found = false;
unsigned find = 0;
for(cii = index.begin(); cii != index.end(); cii++)
{
temp = *cii;
find = temp.find(SubString);
if(find != std::string::npos)//running.find()
{
cout << find << endl;
cout << *cii << endl;
found = true;
}
else
{
if((cii == index.end()) && found)
{
cout << "Not foundn";
found = false;
}
}
}
}
int main()
{
vector<string> index;
ifstream myReadFile;
string str, running;
myReadFile.open("example.txt");
char output[100];
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
while( std::getline( myReadFile, str ) )
{
index.push_back(str);
}
}
}
while(running != "END")
{
cout << "To Quit type:- ENDn";
cin >> running;
if(running == "END")
{break;}
else
{
Search(running, index);
}
}
myReadFile.close();
return 0;
}
查看std::string::find引用。Find有第二个参数,即搜索开始的位置。因此,只需将find放入循环中,并将前一个find的结果作为第二个参数,直到find返回std::string::npos。类似以下语句:
int startpos = 0;
int finds = 0;
while ((startpos = yourstring.find(substring, startpos)) != std::string::npos)
++finds;
我终于做到了。我对Search()
函数做了一些改变。查找下面的代码。
void Search(std::string SubString, vector<string> index)
{
vector<string>::const_iterator cii;
string temp;
bool found = false;
unsigned find = 0;
static int n = 0;
for(cii = index.begin(); cii != index.end(); cii++)
{
temp = *cii;
std::string ::size_type pos = 0;
while( (pos = temp.find( SubString, pos ))
!= std::string::npos )
{
n++;
pos += SubString.size();
cout << pos << " ";
}
if(n)
{
cout << " n ";
cout << *cii << endl;
found = true;
}
else
{
if((cii == index.end() - 1) && !found)
{
cout << "Not foundn";
found = false;
}
}
n = 0;
}
}
相关文章:
- 如何将元素添加到向量的字符串位置
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 返回员工和工资(给定位置子字符串)
- 将文件复制到自定义位置,存在字符串转换问题
- 替换字符串位置 X 中的单词C++
- 在特定位置为字符串添加空格
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 如何在另一个字符串的x位置插入一个字符串?
- 我如何知道字符串中字符相对于英文字母的位置值?
- C++ - 重置字符串流不会重置获取位置或清除标志吗?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何从字符串向量中选择第 n 个位置?
- 如何从输入字符串中提取特定位置的字符?
- C++字符串_Xout_of_range("无效的字符串位置");
- 将字符数复制到新字符串位置的字符串操作,例如 S[0]
- 如何从字符串位置构造CSTRING/STD :: String
- 如何在 boost::regex 中找到子匹配的字符串位置
- 空字符串位置返回为*
- 如果我将一个值赋给一个目前不使用的字符串位置,究竟会发生什么?