Vlada Misici
Vlada Misici

Reputation: 83

strchr for multiple characters?

How can I check if two char arrays have any characters in common ? Obviously strchr won't work in this case because it can only search for one character but I used it to give you an idea about what I want to do.

#include <iostream>
using namespace std;
int main ()
{
    char text[]="example text",
         find_this[]={'p','t','e','\0'};
    if (strchr(text,find_this))
        cout<<"Found!";
    return 0;
}

Upvotes: 1

Views: 630

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

Like this:

#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
    char text[]      = "example text";
    char find_this[] = "pte";

    auto it = std::find_first_of(
        std::begin(text), std::end(text),
        std::begin(find_this), std::end(find_this)-1
    );

    if (it != std::end(text))
       std::cout << "Found!";
}

(live demo)

Notice that I reduce the find_this range by one, to discount its null terminator (as that's assuredly present in the input range!). If I were clever I'd just use a range that discounts the null terminator in both cases. You can do that yourself.

Upvotes: 2

Related Questions