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?
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].*$")) { ... }
How about this for brevity?
if (0 <= "ABCDEFGHI".indexOf(string.charAt(0))) {
// string starts with a character between 'A' and 'I' inclusive
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With