Check if a String is a Valid Binary Number in C
You can check if a string is a valid binary number in C by verifying that every character in the string is either ‘0’ or ‘1’. This can be accomplished using different approaches such as iterating through the string with a loop or utilizing built-in functions like strspn()
to ensure the string contains only binary digits.
1. Checking Binary Number using a For Loop
In this example, we will iterate over each character of the string using a for
loop to check if it is either ‘0’ or ‘1’.
main.c
#include <stdio.h>
#include <string.h>
int isValidBinary(char *str) {
int i;
int len = strlen(str);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1') {
return 0;
}
}
return 1;
}
int main() {
char binaryStr[] = "1010101";
if (isValidBinary(binaryStr)) {
printf("Valid Binary Number\n");
} else {
printf("Invalid Binary Number\n");
}
return 0;
}
Explanation:
- We include
stdio.h
for input/output andstring.h
for thestrlen()
function. - The function
isValidBinary()
takes a string as input and calculates its length usingstrlen()
. - A
for
loop iterates through each character in the string. The variablei
is used as the loop index. - Inside the loop, an
if
statement checks whether the current character is not ‘0’ and not ‘1’. If so, the function returns0
(indicating an invalid binary string). - If all characters are valid, the function returns
1
. - In the
main()
function, the binary string is defined and passed toisValidBinary()
, and the result is printed usingprintf()
.
Output:
Valid Binary Number
2. Checking Binary Number using the strspn()
Function
In this example, we will use the strspn()
function from the string.h
library to verify if the string is composed entirely of ‘0’ and ‘1’ characters.
main.c
#include <stdio.h>
#include <string.h>
int main() {
char binaryStr[] = "1100110";
// Check if the length of the string is equal to the length of the segment that contains only '0' and '1'
if (strlen(binaryStr) == strspn(binaryStr, "01")) {
printf("Valid Binary Number\n");
} else {
printf("Invalid Binary Number\n");
}
return 0;
}
Explanation:
- We include
stdio.h
for standard I/O functions andstring.h
forstrlen()
andstrspn()
. - In the
main()
function, a binary stringbinaryStr
is defined. - The function
strspn(binaryStr, "01")
calculates the number of consecutive characters at the beginning ofbinaryStr
that are either ‘0’ or ‘1’. - We compare the result of
strspn()
with the total length of the string obtained bystrlen(binaryStr)
. - If both values are equal, it confirms that every character in the string is a binary digit, and we print “Valid Binary Number”.
- If not, we print “Invalid Binary Number”.
Output:
Valid Binary Number
Conclusion
In this tutorial, we demonstrated two methods to check if a string is a valid binary number in C. The first method uses a for
loop to examine each character individually, while the second method leverages the strspn()
function to validate the string in a concise manner.