Search for text in a String as a "like"

1

I want to do a text search, like the ones I do in MySQL. Ex: LIKE "9% 4"

I tried to implement a find_if() , but without success.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
   int n;
   string a;

   cin >> n;

   while(n--)
   {
        cin >> a;
        if(a.find("35") != string::npos)
            cout << "-" << endl;
        else if(a.find("190") != string::npos)
            cout << "?" << endl;
        else if(find_if(a.begin(), a.end(), "9*4") != a.end())
            cout << "*" << endl;
        else
            cout << "+" << endl;
   }

   return 0;
}

I can scroll through the whole string and search for "9 * 4" can be any number, but I think you should have a smarter way to do that.

    
asked by anonymous 12.07.2016 / 09:44

1 answer

1

You can do this:

if (a[0] == '9' && a[a.size() - 1] == '4')

If you want to make it easy to accept patterns with more than one character:

auto patternBegin = "9";
auto patternEnd = "4";
if (a.size() > patternBegin.size() && a.size() > patternEnd.size() &&
    equals(patternBegin.begin(), patternBegin.end(), a.end()) &&
    equals(patternEnd.rbegin(), patternEnd.rend(), a.rbegin()))

Of course, if you need something more complex you will need a more sophisticated algorithm. This case has one pattern at the beginning and another at the end, but it could have several patterns spread across string , it would have to handle all of this.

    
12.07.2016 / 13:09