表示数值的字符串

问题描述

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。

思路分析

核心思路就是分情况讨论,主要分为三类:整数、浮点数和科学计数法。
对于整数的判断,就是字符串中没有出现非0到9的字符即可,否则返回错误
对于浮点数,只要考虑整数后面出现一个小数点,而后面的判断与整数相同,
对于科学计数法,就是e和E后其后面的字符串与整数一样,同时如果后面没有数字是不被允许的

码上有戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public boolean isNumeric(char[] str) {
if(str==null||str.length==0)return false;
int index=0;
int length=str.length;
while(index<length&&str[index]==' ')index++;
if(index>=length)return false;
while(str[length-1]==' ')length--;
if(str[index]=='+'||str[index]=='-')index++;
if(index>=length)return false;
while(index<length&&str[index]>='0'&&str[index]<='9')index++;
if(index==length) return true;
int index2=index;
if(str[index]=='.'){
index++;
if(index==length)return true;
index2=index;
while(index<length&&str[index]>='0'&&str[index]<='9')index++;
if(index==index2) return false;
if(index==length) return true;
}
if(str[index]=='e'||str[index]=='E'){
index++;
if(index==length)return false;
if(str[index]=='+'||str[index]=='-')index++;
index2=index;
while(index<length&&str[index]>='0'&&str[index]<='9')index++;
if(index==index2) return false;
if(index==length) return true;
}
return false;
}

热评文章