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

前端 未结 6 1173
暖寄归人
暖寄归人 2020-11-29 18:13

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 abov

6条回答
  •  被撕碎了的回忆
    2020-11-29 18:51

    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.

提交回复
热议问题