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 :
Frequently Asked:
- Check if all elements in array are false in C++
- Create an Array of Strings in C++
- How to Sort an Array of structs in C++?
- How to return an Array from a function in C++
Yes, Array contains only empty strings
Summary
Today we learned about a way to check if array contains only empty strings in C++. Thanks.