題目:請實現(xiàn)一個函數(shù)用來判斷字符串是否表示數(shù)值(包括整數(shù)和小數(shù))。例如,字符串“+100”、“5e2”、“-123”。
解題思路:表示數(shù)值的字符串的模式為A[.[B]][e|EC]和.[B][e|EC],其中A可能為以'+|-'開頭的整數(shù),B為整數(shù),C與A相同。在判斷一個字符串是否符合上述表達式的時候,首先從頭到尾掃描字符串,先判斷A,在遇到小數(shù)點以后,再開始判斷B,在碰到e或者E的時候,開始判斷C。
public class Numeric {
int index = 0;
public boolean isNumeric(char[] str){
if(str==null) return false;
boolean numermic = scanInteger(str,index);
if(str[index]=='.'){
index++;
numermic = scanUnsigendInteger(str,index)||numermic;
}
if(str[index]=='e'||str[index]=='E'){
index++;
numermic = numermic&&scanInteger(str,index);
}
if(index==str.length) return numermic;
else return false;
}
public boolean scanInteger(char[] str,int index){
if(str[index]=='+'||str[index]=='-'){
index++;
}
return scanUnsigendInteger(str ,index);
}
public boolean scanUnsigendInteger(char[] str,int index){
int firstIndex = index;
while(str[index]>='0'&&str[index]<='9')
index++;
return index>firstIndex;
}
}