在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