Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if string starts with letters A through I

I've got a simple java assignment. I need to determine if a string starts with the letter A through I. I know i have to use string.startsWith(); but I don't want to write, if(string.startsWith("a")); all the way to I, it seems in efficient. Should I be using a loop of some sort?

like image 465
Archey Avatar asked Dec 16 '11 20:12

Archey


2 Answers

You don't need regular expressions for this.

Try this, assuming you want uppercase only:

char c = string.charAt(0);
if (c >= 'A' && c <= 'I') { ... }

If you do want a regex solution however, you can use this (ideone):

if (string.matches("^[A-I].*$")) { ... }
like image 57
Mark Byers Avatar answered Sep 27 '22 17:09

Mark Byers


How about this for brevity?

if (0 <= "ABCDEFGHI".indexOf(string.charAt(0))) {
    // string starts with a character between 'A' and 'I' inclusive
}
like image 26
rsp Avatar answered Sep 27 '22 16:09

rsp