Check if Any element in Array is in String in C++

This tutorial will discuss about a unique way to check if any element in array is in string in C++.

Suppose we have an array of strings, and a string value. Like this,

std::string arr[] = {"This", "is", "some", "random", "text", "today"};
std::string strValue = "Goofy is the Last Warrior";

Now we want to check if any string element of array arr is in the string strValue.

We can use the STL Algorithm std::any_of() for it. For this we will pass following arguments,

  • Iterator pointing to the start of array.
  • Iterator pointing to the end of array.
  • A Lambda function, which accepts a string as argument, and checks if this string exists in a specific string i.e. strValue.

The std::any_of() function will apply the given lambda function on all the elements of array. If the lambda function returns true for any element, then any_of() function will also return true, which means that atleast one string in array is present in the main string i.e. strValue.

Let’s see the complete example,

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

int main()
{
    std::string arr[] = {"This", "is", "some", "random", "text", "today"};

    std::string strValue = "Goofy is the Last Warrior";

    // Check if any element in array is in a given string
    bool result = std::any_of(
                        std::begin(arr),
                        std::end(arr),
                        [&strValue](const std::string& str) {
                                     return strValue.find(str) != std::string::npos;
                        });


    if (result)
    {
        std::cout << " Yes, at least one element of Array is present in a given string" << std::endl;
    }
    else
    {
        std::cout << " No, none of the Array element is present in a given string" << std::endl;
    }

    return 0;
}

Output :

Yes, at least one element of Array is present in a given string

Summary

Today we learned about several ways to check if any element in array is in string in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top