How to check if a string is a valid identifier or not in C++?

In this tutorial, we will learn how we can check if a string is a valid identifier or not in C++ programming. We are going to see it with an example code snippet. So stay here and keep reading this article…

Now to check whether a string is a valid identifier or not in C++. First, let us understand what is a valid identifier in C++.

A string can be a valid identifier if it’s initial(first) letter is either an underscore(_) or lowercase alphabet(‘a’-‘z’) or uppercase alphabet(‘A’-‘Z’). Followed by after initial letter, all the next letters can be a combination of either digit(‘0’-‘9’), lowercase alphabets(‘a’-‘z’), uppercase alphabets(‘A’-‘Z’) or underscore(_).

Above all, the letters followed by an initial letter should not have any spaces( ) and the special symbols($,&,@.^, etc).

Now let us understand it more clearly with a program.

//illustrating how to check whether
//a string is valid identifier or not.
#include <bits/stdc++.h> 
using namespace std;

int main()

{

string s;
int c=0,flagv;

cout<<"enter any string: ";
cin>>s;  //input any string

//check whether it is a valid identifier or not
if( (s[0]>='a'&&s[0]<='z')
    ||
    (s[0]>='A'&&s[0]<='Z')
    ||
    (s[0]=='_') )
 {
   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]=='_') )

     {
 c++;

     }  }

    if(c==s.length())

    {

      flagv=0;

    }
 }

 else

 {

  flagv=1;

 } 

//if flagv=1 then string is not a valid identifier

if(flagv==1)

 cout<<s<<"is not valid identifier";

//otherwise string is a valid identifier

else
 
 cout<<s<<" is valid identifier";
 
return 0;
}

Read the comments in the program above for better understanding.

The above code displays the following output i.e., either string is a valid identifier or not a valid identifier.

Some of the valid identifiers are,

1. enter any string:
   abc_
   abc_ is valid identifier.

2. enter any string:
   Amc876_d
   Amc876_d is valid identifier.

3. enter any string:
   _hi777
   _hi777 is valid identifier.

Some of the string which is not valid identifiers are as shown below,

1. enter any string:
   %defA_c
   %defA_c is not valid identifier.

2. enter any string:
   %@^9_8 
   %@^9_8 is not valid identifier.

 

Recommended articles:

Random Alphanumeric String Generation in C++

Python program to check if a string is a valid identifier or not

Leave a Reply

Your email address will not be published. Required fields are marked *