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.

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of