I have a string, and I need to find the last occurrence of any alphanumeric char in this string. Whichever the last alphanumeric character is in the string, I want that index. For
text="Hello World!- "
the output would be the index of 'd'
text="Hello02, "
the output would be the index of '2'. I understand I could do it in a 'brute force' kind of way, checking for every letter and every number and finding the highest index, but I'm sure there's a neater way to do it, but I can't find it.
This will work as expected and it will even work on almost all Unicode characters and numbers:
public static final int lastAlphaNumeric(String s) {
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if (Character.isLetter(c) || Character.isDigit(c))
return i;
}
return -1; // no alphanumeric character at all
}
It is also much faster than the other answers ;)
Use regex to do the heavy lifting.
To get the index of the last alphanumeric character (-1
if no alphanumerics in the string):
int index = str.replaceAll("[^a-zA-Z0-9]*$", "").length() - 1;
To get the character itself:
String last = str.replaceAll("[^a-zA-Z0-9]*$", "").replaceAll(".(?!$)", "");
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