Java – lastindexof() finds the last alphanumeric character
•
Java
I have a string in which I need to find the last alphanumeric character No matter what the last alphanumeric character in the string is, I want that index about
text="Hello World!- "
The output will be the index of'd '
text="Hello02,"
The output will be an index of '2' I know I can do it in a "brute force" way, check each letter and number and find the highest index, but I'm sure there's a simpler way to do it, but I can't find it
Solution
This will work as expected, and it can 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 other answers;)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码