Determine if string starts with letters A through I

Archey picture Archey · Dec 16, 2011 · Viewed 52.4k times · Source

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?

Answer

Mark Byers picture Mark Byers · Dec 16, 2011

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].*$")) { ... }