Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out if first character of a string is a number?

Tags:

java

string

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.

like image 275
Omnipresent Avatar asked Aug 03 '09 15:08

Omnipresent


People also ask

How do you check if a character in string is a number?

We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.

How do you check if a string starts with a letter or number in Java?

Java String startsWith() Method The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s).


1 Answers

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'); 

Or the slower regex solutions:

s.substring(0, 1).matches("\\d") // or the equivalent s.substring(0, 1).matches("[0-9]") 

However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

To make the entire condition one line and avoid length checks, you can alter the regexes to the following:

s.matches("\\d.*") // or the equivalent s.matches("[0-9].*") 

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.

like image 124
Michael Myers Avatar answered Sep 21 '22 19:09

Michael Myers