Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside a std::string, is it possible to find the first of a set of strings without using a loop?

Tags:

c++

string

find

stl

Inside a std::string, is it possible to find the first of a set of strings without using a loop?

E.g.:

std::string str("aaa bbb ccc ddd eee fff ggg");
std::vector<std::string> vs;
vs.push_back("ccc");
vs.push_back("fff");
size_t pos = 0
pos = str.find(vs, pos);      //< pseudo code

Thank you!

like image 778
Pietro Avatar asked Dec 29 '22 04:12

Pietro


1 Answers

You could split the string (using a stringstream) into a vector and then use std::find_first_of with the four iterators.

Here is a complete code example

#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
#include <iterator>

using namespace std;

int main(void)
{
  string str("aaa bbb ccc ddd eee fff ggg");
  vector<string> vs;
  vs.push_back("ccc");
  vs.push_back("fff");
  vector<string> scheck;

  istringstream instr(str);
  copy(istream_iterator<string>(instr),
       istream_iterator<string>(),
       back_inserter(scheck));

  vector<string>::iterator it = find_first_of (scheck.begin(), scheck.end(), vs.begin(), vs.end());
  if (it != scheck.end())
    cout << "first match is: " << *it << endl;

  return 0;
}
like image 77
Nim Avatar answered Jan 18 '23 15:01

Nim