How to check if a string only contains one ('1') and zero ('0') in C

2 Answers

0 votes
#include <stdio.h>
#include <stdbool.h>
 
bool isBinary(const char* str) {
    for (int i = 0; str[i]; i++)
        if (str[i] != '0' && str[i] != '1')
            return false;
    return true;
}
 
int main(void) {
 
    char s1[] = "0110001110111";
    puts(isBinary(s1) ? "yes" : "no");
     
    char s2[] = "011011189100";
    puts(isBinary(s2) ? "yes" : "no");
 
    return 0;
}
 
 
 
 
/*
run:
 
yes
no
 
*/

 



answered Apr 11, 2023 by avibootz
edited Apr 11, 2023 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isBinary(const char* str) {
    if (!*str) {
        return false;
    }

    return str[strspn(str, "01")] == '\0';
}

int main(void) {

    char s1[] = "0110001110111";
    puts(isBinary(s1) ? "yes" : "no");
    
    char s2[] = "011011189100";
    puts(isBinary(s2) ? "yes" : "no");

    return 0;
}




/*
run:

yes
no

*/

 



answered Apr 11, 2023 by avibootz

Related questions

...