In Java is there a way to find out if first character of a string is a number?
One way is
string.startsWith("1")
and do the above all the way till 9, but that seems very inefficient.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Note that this will allow any Unicode digit, not just 0-9. You might prefer:
Or the slower regex solutions:
However, with any of these methods, you must first be sure that the string isn’t empty. If it is,
charAt(0)andsubstring(0, 1)will throw aStringIndexOutOfBoundsException.startsWithdoes not have this problem.To make the entire condition one line and avoid length checks, you can alter the regexes to the following:
If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.