Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lastIndexOf() to find last alphanumeric character

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.

like image 246
Iverie Avatar asked Jan 22 '14 12:01

Iverie


2 Answers

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

like image 85
Njol Avatar answered Sep 20 '22 01:09

Njol


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(".(?!$)", "");
like image 43
Bohemian Avatar answered Sep 19 '22 01:09

Bohemian