If you don't need regex
you can do it just by looping through (My reccomendation)
public int findFirstLetterPosition(String input) {
char c;
for (int i = 0; i < input.length(); i++) {
c = input.charAt(i);
if ( (c >= 'a' && c <= 'z') || (c >= 'A' || c <= 'Z') ) {
return i;
}
}
return -1; // not found
}
EDIT
In response to some comments, you could also do this less explicitly using a built in static method, and add some handling for non-ASCII characters using isLetter
:
public int findFirstLetterPosition(String input) {
for (int i = 0; i < input.length(); i++) {
if (Character.isLetter(input.charAt(i))) {
return i;
}
}
return -1; // not found
}
You can also use isAlphabetic
:
public int findFirstLetterPosition(String input) {
for (int i = 0; i < input.length(); i++) {
if (Character.isAlphabetic(input.charAt(i))) {
return i;
}
}
return -1; // not found
}
The latter includes some alphabetic characters from other languages which are iffy on whether to box them as characters or phrases
ref: Character.isLetter, Character.isAlphabetic