Check each character in a string for a condition in C++

This tutorial will discuss about a unique way to check each character in a string for a condition in C++.

To check if each character in string satisfies a condition, we need to iterate over all the characters in string and check each character one by one. Although, we can use a for loop for this, but as we are using C++, so its better to use an existing STL Algorithm i.e. std::all_of(). Like this,

std::string strValue = "test string";

// Check if all characters in string 
// are lowercase characters
bool result = std::all_of(
                strValue.begin(),
                strValue.end(),
                condition);

In this case, all_of() function accepts three arguments,

  • Iterator pointing to the first character of string.
  • Iterator pointing to the end of string.
  • A Callback function, that accepts a character as an argument, and checks if the given character statisfies the condition or not.

The all_of() function applies the given callback function on all the characters of string (given range), and returns true, if the given callback function returns true for all the characters. This callback function can be a global function, class member function or a lambda function.

In the below example, We have used the all_of() function to check if all the characters in a string are lowercase.

Let’s see the complete example,

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

// Returns true if given character
// is a lowercase character
bool condition(const char& ch)
{
    return ::islower(ch);
}

int main()
{
    std::string strValue = "sample";

    // Check if all characters in string
    // are lowercase characters
    bool result = std::all_of(
                    strValue.begin(),
                    strValue.end(),
                    condition);

    if(result)
    {
        std::cout << "All characters in string matches the condition \n";
    }
    else
    {
        std::cout << "All characters in string does not matches the condition \n";
    }

    return 0;
}

Output :

All characters in string matches the condition

Summary

Today we learned about several ways to check each character in a string for a condition 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