Checking Type of String

Checking Type of String” is a problem to check whether the given string of length ‘n’ is alphabetic or numeric or alphanumeric.

Alphabetic String: An alphabetic string is a type of string which contains only alphabets.

Numeric String: A numeric string is a type of string which contains only numbers.

Alphanumeric String: An alphanumeric string is a type of string which contains both alphabets and numbers.

Example:

```INPUT:
dffgdassAA
OUTPUT:
dffgdassAA is an alphabetic string

INPUT:
Sdfjhd23sd1
OUTPUT:
Sdfjhd23sd1 is an alphanumeric string

INPUT:
123434332
OUTPUT:
123434332 is a numeric string.```

The steps required to check whether string is alphabetic or numeric or alphanumeric is as follows:

1. Initialize two flag variables, namely, alphabetic and numeric with 0.
2. Scan the complete string and check whether encountered character is alphabet or number.
3. If encountered character is alphabet, set flag variable alphabetic with 1, else if encountered character is number, set flag variable numeric with 1.
4. If alphabetic is set to 1 and numeric is set to 0, then given string is alphabetic string.
5. If alphabetic is set to 0 and numeric is set to 1, then given string is numeric string.
6. If alphabetic is set to 1 and numeric is set to 1, then given string is alphanumeric string.

C++ Program to check whether string is alphabetic or numeric or alphanumeric is as follows:

```#include<bits/stdc++.h>
#define len 1000
using namespace std;
int main()
{
char str[len];
cout<<"Enter the string:\n";
cin>>str;
int alphabetic = 0;
int numeric = 0;
for(int i = 0; i < 1000 && str[i]!='\0'; i++)
{
if(str[i]>='0' && str[i]<='9')
numeric = 1;
else if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
alphabetic = 1;
}
if(numeric == 0 && alphabetic == 1)
cout<<str<<" is an alphabetic string";
else if(numeric == 1 && alphabetic == 0)
cout<<str<<" is a numeric string";
else if(numeric == 1 && alphabetic == 1)
cout<<str<<" is an alphanumeric string";
}

```
```OUTPUT:
Enter the string:123
123 is a numeric string
Time Complexity:
O(n), where n is a length of string.```

Related Posts: