Determine if a string starts with a number in Java
This post will check if a string starts with a number or not in Java.
1. Naive solution
A naive solution is to extract the first character from the given string using the charAt() method and validate that character falls under the numeric ASCII range or not.
|
1 2 3 4 5 6 7 8 9 10 |
class Main { public static void main(String[] args) { String str = "12ABC"; char ch = str.charAt(0); System.out.println(ch >= '0' && ch <= '9'); // true } } |
2. Using Character.isDigit() method
The recommended solution is to use the Character.isDigit(char) method to check if the first character of the string is a digit or not. Note that this also supports all Unicode digits.
|
1 2 3 4 5 6 7 8 |
class Main { public static void main(String[] args) { String str = "12ABC"; System.out.println(Character.isDigit(str.charAt(0))); // true } } |
3. Using Regex
Another plausible way of determining whether a string ends with a number or not is using regex. This approach is not recommended as regular expressions are extremely slow.
|
1 2 3 4 5 6 7 8 9 10 |
class Main { public static void main(String[] args) { String str = "12ABC"; System.out.println(str.matches("\\d.*")); // true System.out.println(str.matches("[0-9].*")); // true } } |
Note that all the above solutions assume that the string is not empty. If the string is empty, the program will throw a StringIndexOutOfBoundsException.
That’s all about checking if a string starts with a number in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)