Search text in a String as a "like"

Asked

Viewed 195 times

2

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 go all the way string manually and search for "9*4"could be any number, but I believe there must be a smarter way to do that.

1 answer

2


You can do it like 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()))

I put in the Github for future reference.

Of course, if you need anything more complex, you’ll need a more sophisticated algorithm. This case has one pattern at the beginning and one at the end, but it could have several patterns spread across string, would have to treat all this.

  • 1

    Thanks for the answer, in the first code you posted, if the entry was 94 it would enter in it too, wouldn’t it? I forgot to mention also that there will only be one number between 9 and 4.

  • 1

    I answered what was asked. If you can only have one character is quite different from what is in the question. Then it is simple, just see if the size of the string is 3 too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.