Check whether the given string is a valid identifier | C ++ implementation of the approach ; Function that returns true if str is a valid identifier ; If first character is invalid ; Traverse the string for the rest of the characters ; String is a valid identifier ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( string str , int n ) { if ( ! ( ( str [ 0 ] >= ' a ' && str [ 0 ] <= ' z ' ) || ( str [ 0 ] >= ' A ' && str [ 0 ] <= ' Z ' ) str [ 0 ] == ' _ ' ) ) return false ; for ( int i = 1 ; i < str . length ( ) ; i ++ ) { if ( ! ( ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) || ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) || ( str [ i ] >= '0' && str [ i ] <= '9' ) str [ i ] == ' _ ' ) ) return false ; } return true ; } int main ( ) { string str = " _ geeks123" ; int n = str . length ( ) ; if ( isValid ( str , n ) ) cout << " Valid " ; else cout << " Invalid " ; return 0 ; }