Determine if a string ends with a number or not in Java

In this post, we will check if a string ends with a number or not.


1. Naive

Naive solution would be to extract first character from the given string using charAt() method and validate that character falls under numeric ASCII range or not.


Download   Run Code


2. Character#isDigit()

The recommended solution is to use the Character.isDigit(char) method to check if first character of the String is a digit or not. Note that this also support all Unicode digits.


Download   Run Code


3. Regex

Another plausible way of determining whether a string ends with a number or not is using regex. This approach is not recommend as regexes are very slow.


Download   Run Code

Note that all above solutions assumes that the string is not empty. If the String is empty, the program will throw a StringIndexOutOfBoundsException.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of