Check if a String is Binary in C++

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

To check if a string contains a Binary value or not, we need to confirm if string contains only 0s or 1s. For that, we can use the STL Algorithm all_of(). we will pass following arguments in it,

  • An Iterator pointing to the first character of string.
  • An Iterator pointing to the end of string.
  • A Lambda function, which accepts a character as argument, and returns true if the character is either ‘0’ or ‘1’.

The all_of() function will iterate over all the characters in string, and will apply the given lambda function on each character. If all the values returned by all the lambda function calls are true, then it means all characters in string are either ‘0’ or ‘1’. It means that the given string contains a binary value.

Let’s see the complete example,

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

// Returns true, if given string is a
// binary string
bool IsBinary(const std::string& strValue)
{
    // Check if string is non empty
    bool result = !strValue.empty();

    // Check if all characters in string
    // are either '1' or '0'
    result = result && std::all_of(
                            strValue.begin(),
                            strValue.end(),
                            [](auto ch){
                                return ch == '1' || ch == '0';
                            });
    return result;
}

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

    // Check if string is a Binary String
    if(IsBinary(strValue))
    {
        std::cout << "Yes, string is a Binary String \n";
    }
    else
    {
        std::cout << "No, string is not a Binary String \n";
    }

    return 0;
}

Output :

Yes, string is a Binary String

Summary

Today we learned about several ways to check if a string is binary 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