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

</>
Copy
#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:

  1. We include stdio.h for input/output and string.h for the strlen() function.
  2. The function isValidBinary() takes a string as input and calculates its length using strlen().
  3. A for loop iterates through each character in the string. The variable i is used as the loop index.
  4. Inside the loop, an if statement checks whether the current character is not ‘0’ and not ‘1’. If so, the function returns 0 (indicating an invalid binary string).
  5. If all characters are valid, the function returns 1.
  6. In the main() function, the binary string is defined and passed to isValidBinary(), and the result is printed using printf().

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

</>
Copy
#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:

  1. We include stdio.h for standard I/O functions and string.h for strlen() and strspn().
  2. In the main() function, a binary string binaryStr is defined.
  3. The function strspn(binaryStr, "01") calculates the number of consecutive characters at the beginning of binaryStr that are either ‘0’ or ‘1’.
  4. We compare the result of strspn() with the total length of the string obtained by strlen(binaryStr).
  5. If both values are equal, it confirms that every character in the string is a binary digit, and we print “Valid Binary Number”.
  6. 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.