Check if Array Contains Only Empty Strings in C++

This tutorial will discuss about a unique way to check if array contains only empty strings in C++.

Suppose we have a string array. Like this,

const char* arr[] = {"", "", "", "", "", "", ""};

Now, we want to check if all the strings in this array are empty or not.

For this, we are going to use the std::all_of() function from STL Algorithms. It acccepts three arguments,

  • The first two arguments are the start and the end iterator of the array.
  • The third argument is a Lambda function which accepts a string and returns true if the given string is empty.
// Check if all the strings in array are empty
bool result = std::all_of(
                    std::begin(arr),
                    std::end(arr),
                    [](const std::string& str) {
                        return str.empty();
                    });

The std::all_of() function will apply the given Lambda function on all the strings in the array, and if the Lambda function returns true for each element of the array, then the std::all_of() function will also return true, which means that all the strings in array are empty.

Let’s see the complete example,

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

int main()
{
    // An array of strings
    const char* arr[] = {"", "", "", "", "", "", ""};

    // Check if all the strings in array are empty
    bool result = std::all_of(
                        std::begin(arr),
                        std::end(arr),
                        [](const std::string& str) {
                            return str.empty();
                        });

    if(result)
    {
        std::cout << "Yes, Array contains only empty strings \n";
    }
    else
    {
        std::cout << "No, Array does not contain only empty strings \n";
    }
    return 0;
}

Output :

Yes, Array contains only empty strings

Summary

Today we learned about a way to check if array contains only empty strings 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