如何确定字符串的第一个字符是否为数字? [英] How do I find out if first character of a string is a number?
问题描述
在Java中有没有办法找出字符串的第一个字符是否为数字?
In Java is there a way to find out if first character of a string is a number?
一种方法是
string.startsWith("1")
并一直做到9点,但这似乎效率很低。
and do the above all the way till 9, but that seems very inefficient.
推荐答案
Character.isDigit(string.charAt(0))
请注意这将允许任何 Unicode数字,而不仅仅是0-9。您可能更喜欢:
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]")
但是,使用上述任何一种方法,您必须先确保字符串不为空。如果是, charAt(0)
和 substring(0,1)
将抛出的StringIndexOutOfBoundsException
。 startsWith
没有此问题。
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.
这篇关于如何确定字符串的第一个字符是否为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!