Check if all elements in array are in string in C++

This tutorial will discuss about a unique way to check if all elements in array are in string in C++.

To check if all the strings from an array are present in another string, we will use the std::all_of() function from STL Algorithms.

The std::all_of() function accepts three arguments,

  • Iterator pointing to the start of a sequence.
  • Iterator pointing to the end of a sequence.
  • A Callback or Lambda function which accepts a value of same type as the type of sequence, and returns a boolean value.

The std::all_of() function will apply the given Lambda function on all the elements of the sequence and it returns true if the callback function returns true for all the elements of the sequence.

So to check if all elements of an array are present in a string we will pass this start and end iterators of array to the std::all_of() function as first two arguments and as the 3rd argument we will pass a Lambda function, which accepts a string as an argument and then then checks if the given string exists in the main string or not. If not, then it will return false, otherwise it will return true. The std::all_of() function will return true, if the given Lambda function returns true for all the elements of the array.

This way we can check if all the string elements in an array are present in another string or not.

Let’s see the complete example,

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

int main() {
    std::string arr[] = { "is", "sample", "This" };

    std::string strValue = "This is a sample text";

    // Check if all the strings in array are present in the given string
    bool result = std::all_of(
                        std::begin(arr),
                        std::end(arr),
                        [&strValue](const std::string& subStr){
                            return strValue.find(subStr) != std::string::npos;
                        });

    if (result)
    {
        std::cout << "Yes, all strings in the array are present in a given string." << std::endl;
    } else
    {
        std::cout << "No, all strings in the array are not present in a given string." << std::endl;
    }

    return 0;
}

Output :

Yes, all strings in the array are present in a given string.

Summary

Today we learned about several ways to check if all elements in array are 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