Hey to you all,
I have this loop that goes through a string and gets every letter and assigns it to a char.
I want to check if this char is an A or B or C or D, etc …
How do you check if the char is a specific letter?
Here is some code:
String alpha = "ABSDROP";
for (int i = 0; i< alpha.length(); i++) {
char c = alpha.charAt(i);
//System.out.println(c);
if (c == "A"||"B"||"D") { //I don't get how to check this part???
//do something...
}
1 Like
String alpha = “ABSDROP”;
for (int i = 0; i< alpha.length(); i++) {
char c = alpha.charAt(i);
//System.out.println(c);
if (c == 'A'|| c=='B' || c=='D') {
//do something...
}
1 Like
You can also use ASCII value of alphabets in the if condition. Another way of checking would be using switch case.
Thanks it was the single quotes. I used double ones.
You can also use switch case, such as:-
switch©
{
case ‘A’:
//do something
break;
case ‘B’://do something
break;
…etc.
}
try this if you’re using java:
if(Character.isLetter(char_variable))
{
System.out.println(char_variable+“is a alphabet!”);
}
else
{
System.out.println(char_variable+“is not a alphabet!”);
}
1 Like