Reputation:
Sorry , I am using an ancient compiler
#include <iostream.h>
#include <conio.h>
#include <ctype.h>
void main()
{
char s[6] = "mOh1t*";
int u = 0 , l=0 , d=0 , sp=0 , t = 0;
for (int x = 0 ; s[x] ; x++)
{
if (isupper(s[x]))
u++;
else if(islower(s[x]))
l++;
else if (isdigit(s[x]))
d++;
t++;
}
sp = t - (u+l+d);
cout<<"t:"<<t;
cout<<"u:"<<u;
cout<<"l:"<<l;
cout<<"d:"<<d;
cout<<"sp:"<<sp;
getch();
}
The above code clearly counts the number of alphabets(uppercase and lowercase) , number of digits and number of special characters in a string.
I was wondering if the same is possible without using if statements/ternary operator/switch case. If yes , could I get a lead ?
Kudos to HoosierEE for the answer
UPDATE: Would it be possible to do the same as hoosierEE's answer without using inbuilt functions?
- A C++ newbie looking to learn
Upvotes: 2
Views: 110
Reputation: 3829
If you just want to avoid if statements, you can treat booleans as 0 and 1 and sum up the characters like so:
for (int x = 0; s[x]; x++)
{
u += isupper(s[x]);
l += islower(s[x]);
d += isdigit(s[x]);
t++;
}
...But as @Angew mentions, you can't rely on the result to be just a 0 or 1 with these functions.
And to answer the UPDATE, here's how you could achieve what you want without stdlib functions:
for (int x = 0; s[x]; x++)
{
u += ((s[x] >= 'A') && (s[x] <= 'Z'));
l += ((s[x] >= 'a') && (s[x] <= 'z'));
d += ((s[x] >= '0') && (s[x] <= '9'));
t++;
}
You could look up the ASCII values and put numbers in there, but I think using character literals is more readable. Personal preference.
You might also consider being a little more strict with your termination condition:
for (int x = 0; s[x] != '\0'; x++)
Upvotes: 4