We will use the new std::search function with strings and try its different variations with searcher objects:
- First, we will include all the necessary headers and declare that we use the std namespace:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>
using namespace std;
- We will print substrings from the positions the search algorithm returns to us, so let's implement a little helper for that:
template <typename Itr>
static void print(Itr it, size_t chars)
{
copy_n(it, chars, ostream_iterator<char>{cout});
cout << 'n';
}
- A lorem-ipsum style string will work as our example string, within which we will search a substring. In this case, this is "elitr":
int main()
{
const string long_string {
"Lorem ipsum dolor sit amet, consetetur"
" sadipscing elitr, sed diam nonumy eirmod"};
const string needle {"elitr"};
- The old std::search interface accepts the begin/end iterators of the string within which we are searching a specific substring and the begin/end iterators of the substring. It then returns an iterator pointing to the substring it was able to find. If it didn't find the string, the returned iterator will be the end iterator:
{
auto match (search(begin(long_string), end(long_string),
begin(needle), end(needle)));
print(match, 5);
}- The C++17 version of std::search does not accept two pairs of iterators but one pair of begin/end iterators and a searcher object. The std::default_searcher takes the begin/end pair of iterators of the substring that we are searching for in the larger string:
{
auto match (search(begin(long_string), end(long_string),
default_searcher(begin(needle), end(needle))));
print(match, 5);
}- The point of this change is that it is easy to switch the search algorithm this way. The std::boyer_moore_searcher uses the Boyer-Moore search algorithm for a faster search:
{
auto match (search(begin(long_string), end(long_string),
boyer_moore_searcher(begin(needle),
end(needle))));
print(match, 5);
}- The C++17 STL comes with three different searcher object implementations. The third one is the Boyer-Moore-Horspool search algorithm implementation:
{
auto match (search(begin(long_string), end(long_string),
boyer_moore_horspool_searcher(begin(needle),
end(needle))));
print(match, 5);
}
}- Let's compile and run our program. We should see the same string everywhere if it runs correctly:
$ ./pattern_search_string
elitr
elitr
elitr
elitr