Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and work.

aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing
BlueHost Web Hosting

Profollica™ is a standout product in the hair regrowth industry.

New Arrival!  Shop NOW for metal eyeglasses at GlassesShop.com!

Bonsai Boy of New York Bonsai Trees and Accessories

DreamCloud The Comfortable Luxury Mattress Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


Liquid Web Cloud VPS Hosting

Disclosure We are a professional Programming & Software Q&A website, that receives compensation from some of the links whose we show you with Information. It means that my content may contain affiliate links.

13,953 questions

18,958 answers

573 users

How to check whether the given string is a valid variable syntax in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool is_valid_variable(char s[]) { 
    if ( !((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[1] <= 'Z') || s[0] == '_')) 
        return false; 
	
    for (int i = 1; i < strlen(s); i++) { 
        if ( !((s[i] >= 'a' && s[i] <= 'z') 
            || (s[i] >= 'A' && s[i] <= 'Z') 
            || (s[i] >= '0' && s[i] <= '9') 
             || s[i] == '_')) 
            return false; 
    } 
  
    return true; 
} 
  
int main() 
{ 
    char s[] = "_num"; 

    if (is_valid_variable(s)) 
        printf("Valid\n");
    else
        printf("Invalid\n");
	
    strcpy(s, "a12"); 
    if (is_valid_variable(s)) 
        printf("Valid\n");
    else
        printf("Invalid\n");
        
    strcpy(s, "1f"); 
    if (is_valid_variable(s)) 
        printf("Valid\n");
    else
        printf("Invalid\n");
        
    strcpy(s, "num-a"); 
    if (is_valid_variable(s)) 
        printf("Valid\n");
    else
        printf("Invalid\n");
	
    return 0; 
} 


/*
run:

Valid
Valid
Invalid
Invalid

*/

 




answered Sep 12, 2019 by avibootz
...