【问题标题】:Using std::search to find multiple occurrence of pattern使用 std::search 查找模式的多次出现
【发布时间】:2014-04-14 13:49:15
【问题描述】:

我想使用函数搜索或其他类似函数来查找给定模式的多次出现。

这是我的代码:

#include <cstring>  
#include <iostream> 
#include <iomanip>  
#include <set>
#include <list>
#include <vector>
#include <map>   
#include <algorithm>
#include <functional>
using namespace std;

int main () {
  std::vector<int> haystack;

  string a = "abcabcabc";
  string b = "abc";
  string::iterator it;
  it = search(a.begin(),a.end(),b.begin(),b.end());

  if(it!=a.end()){
      cout << it-a.begin()<<endl;
  }

  return 0;
}

此代码返回 0 作为模式 "abc" 的第一次出现,想要返回 0、3、6。这将是模式开始的原始字符串中的所有索引。

感谢您的帮助。

【问题讨论】:

标签: c++ search


【解决方案1】:
for(size_t pos=a.find(b,0); pos!=std::string::npos; pos=a.find(b,pos+1)) {
    std::cout << pos << std::endl;
}    

这里直接使用std::basic_string::find(ref)来查找子串的起始位置。

【讨论】:

  • 这段代码每次都从头到尾搜索吗?还是从最后一个位置继续?
  • pos+1继续。
  • 如果要进行不区分大小写的搜索怎么办?在这种情况下, find() 将不起作用。而且我不确定如何在 search() 中推进迭代器。有什么想法吗?
【解决方案2】:

search 函数在第一个字符串 a 中搜索第二个字符串 b 的任何元素。由于您的第二个字符串包含元素 abc,因此代码会将迭代器返回到第一个位置,然后返回到第二个、第三个......

你要使用的是find 函数。它返回一个迭代器,指向与您正在搜索的元素相同的元素。在您的情况下,您在字符串a 中搜索元素abc。所以你必须打电话给

string::iterator it = std::find(a.begin(), a.end(), "abc");
while (it != a.end()) {
    // Do whatever you want to do...
    ++it;
    it = std::find(it, a.end(), "abc");
}

【讨论】:

    【解决方案3】:
    //find first result index
    auto find_index = str.find("st");
    while(string::npos != find_index) {
      cout << "found at: " << find_index << endl;
      //find next
      find_index = str.find("st",find_index+1);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      相关资源
      最近更新 更多