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

1 Answer

0 votes
#include <iostream>
 
using namespace std; 
   
bool isValidVariable(string s) { 
    if ( !((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[1] <= 'Z') || s[0] == '_')) 
        return false; 
   
    for (int i = 1; i < s.length(); 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() 
{ 
    string s = "_num"; 
 
    if (isValidVariable(s)) 
        cout << "Valid" << endl; 
    else
        cout << "Invalid" << endl; 
         
         
    s = "a12"; 
    if (isValidVariable(s)) 
        cout << "Valid" << endl; 
    else
        cout << "Invalid" << endl; 
         
    s = "1f"; 
    if (isValidVariable(s)) 
        cout << "Valid" << endl; 
    else
        cout << "Invalid" << endl; 
         
    s = "num-a"; 
    if (isValidVariable(s)) 
        cout << "Valid" << endl; 
    else
        cout << "Invalid" << endl; 
   
    return 0; 
} 
 
 
/*
run:
 
Valid
Valid
Invalid
Invalid
 
*/

 



answered Sep 12, 2019 by avibootz
edited Sep 12, 2019 by avibootz
...