tags:

views:

901

answers:

1

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.

Edit: After the answer, I found out a regex way to do this as well:

s.substring(0,1).matches("[0-9]")
+21  A: 
Character.isDigit(string.charAt(0));

Note that this will allow any Unicode digit, not just 0-9. You might prefer:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

Edit: However, I neglected to mention that with either of these, you must first be sure that the string isn't empty. If it is, charAt(0) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

Michael Myers
wow. people love upvoting you :) thanks for the answer.
Omnipresent
Why not? It's correct *twice*. :) (Incidentally, I'd encourage you to vote more; voting is an integral part of this site. I see that you have 41 posts but only 19 votes in 7 months.)
Michael Myers
Ha, I'll give you half a vote for each time you are right.
jjnguy