在Java中,有一种方法可以查明字符串的第一个字符是数字吗?如何找出字符串的第一个字符是否是数字?
一种方法是
string.startsWith("1")
,做上述所有的方式,直到9,但似乎非常低效。
在Java中,有一种方法可以查明字符串的第一个字符是数字吗?如何找出字符串的第一个字符是否是数字?
一种方法是
string.startsWith("1")
,做上述所有的方式,直到9,但似乎非常低效。
Character.isDigit(string.charAt(0))
请注意,this will allow any Unicode digit,而不仅仅是0-9。你可能会喜欢:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
或者较慢的正则表达式的解决方案:
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
然而,任何这些方法,必须首先确保该字符串不为空。如果是,charAt(0)
和substring(0, 1)
会抛出StringIndexOutOfBoundsException
。 startsWith
没有这个问题。
要使整个状况一行,并避免长度检查,你可以改变正则表达式为以下内容:
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
如果条件不出现在你的程序紧密循环,小的性能损失因为使用正则表达式不太可能引起注意。
哇。人们喜欢upvoting你:)谢谢你的答案。 – Omnipresent 2009-08-03 15:56:52
为什么不呢?这是正确的*两次*。 :)(顺便说一句,我鼓励你多投;投票是本网站不可或缺的一部分,我看到你有41个职位,但7个月只有19个投票。) – 2009-08-03 16:04:16
哈,我给你半票每次你是对的。 – jjnguy 2009-10-02 16:45:36
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}
正则表达式是非常强大但昂贵的工具。它是有效使用它们来检查,如果第一个字符是一个数字,但它不是那么优雅:)我喜欢这种方式:
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
我只是碰到了这个问题,并认为与该做的解决方案作出贡献不使用正则表达式。
在我来说,我使用一个辅助方法:
public boolean notNumber(String input){
boolean notNumber = false;
try {
// must not start with a number
@SuppressWarnings("unused")
double checker = Double.valueOf(input.substring(0,1));
}
catch (Exception e) {
notNumber = true;
}
return notNumber;
}
可能矫枉过正,但我会尽量避免正则表达式时,我可以。
试试这个代码将帮助你:)
import java.io.*;
public class findDigit
{
public findDigit()
{
String line = "1Hello";
String firstLetter = String.valueOf(line.charAt(0)); //line had 0 to 5 string index
char first = firstLetter.charAt(0);
/*
if (Character.isLetter(first)) //for alphabets
if (Character.isSpaceChar(first)) //for spaces
*/
if (Character.isDigit(first)) // for Digits
{
int number = Integer.parseInt(firstLetter);
System.out.println("This String has digit at first as: "+number);
}
else
{
System.out.println("This String has alphabet at first as: "+firstLetter);
}
}
public static void main(String args[])
{
new findDigit();
}
}
我要提到的正则表达式的方式,但我很害怕,如果我这样做,你会被诱惑去尝试它。 – 2009-08-03 16:26:37