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

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

eg:.

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!

+3
source share
5 answers

You can split a string (using a string stream) into a vector, and then use std::find_first_ofwith 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;
}
+4
source

The simplest solution would be to use a regex library like Boost.Regex, with something like this:

"\\b(ccc|fff)\\b"
+4
source
+2

, , :

str.find() ( "" ) .

, :

size_t pos1 = str.find(vs.begin() , 0);
size_t pos2 = str.find(vs.end() , 0); 
// since you have only ccc and fff , ccc is on begin(), and fff on end()

??? .

edit: , , .

0

, , .

, - vec.begin(), vec.end() str.find , , boost:: bind.

, . - :

std::vector< std::string::size_type > locations;
locations.reserve( vec.size() );
std::transform( vec.begin(), vec.end(), std::back_inserter(locations), boost::bind( &std::string::find, str, _1 ) );

, . , - , , , , , , .

0

Source: https://habr.com/ru/post/1778079/


All Articles