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

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!

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;
}

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

"\\b(ccc|fff)\\b"

Need Your Help

How do I check whether an object's ID is present in an array?

ruby arrays ruby-on-rails-3 logic

Here's the logic I'm trying to write, but I can't find the proper Ruby way to say it:

Selecting Subset of Pandas DataFrame

python pandas

I have two different pandas DataFrames and I want to extract data from one DataFrame whenever the other DataFrame has a specific value at the same time.To be concrete, I have one object called "GDP"

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.