How to check if a given string is binary or not in C++

In this tutorial, we will learn how to check if a given string is binary or not in C++. This problem can be considered as a subset of string problems in which we check for the presence of a particular character in a given string.
We are hereby given a problem in which we have a string and we have to check if the given string is binary or not. By binary string I mean to say that all the characters in the string are either ‘1’s or ‘0’s.

Check for Binary in C++

We have been given a non empty sequence of characters and we will return true if string is binary or false otherwise.
Here we have a variable t denoting no of test cases (i.e. no of strings entered by the user).

//  Binary String CodeSpeedy
#include <bits/stdc++.h>
using namespace std;
// Function StringBinary takes a string input and 
// Returns bool
bool StringBinary(string str);
// Here t is no of test cases 
// That is no of strings given as input
int main()
{
    string str;
    int t;
    scanf("%d\n", &t);
    while (t--)
    {
       cin >> str;
       cout << StringBinary(str) << endl;
    }
    return 0;
}



// Return true if str is binary, else false
bool StringBinary(string str)
{
   for(int i=0;i<str.size();i++)
   {
       if(str[i]!='1' && str[i]!='0')
       return false;
   }
   return true;
}

After inputting the no of test cases, the function StringBinary is called and checks for the following condition

str[i]!='1' && str[i]!='0'

It checks if each character in the array is neither 1 nor 0 then it returns false, and if this is not the case it returns true.
For example:

Input:
2
1010101110
10111012
Output:
1
0

You may also learn:
Separate ‘1’ and ‘0’ in a binary string in C++

Leave a Reply

Your email address will not be published. Required fields are marked *