lastIndexOf() to find last alphanumeric character

Iverie picture Iverie · Jan 22, 2014 · Viewed 7.2k times · Source

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.

Answer

Njol picture Njol · Jan 22, 2014

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 ;)