面试题二十:判断字符串是否表示数值

 1  //整数的格式可以用 A[ .[B]][E|e C]或 .B[E|e C],其中AC都为整数,B是一个无符号整数
 2       //扫描字符串时的索引
 3     int i=0;
 4     public boolean isNumber(String s) {
 5        
 6         if(s==null || s.length()==0)
 7             return false;
 8        
 9         boolean A = scanInteger(s), B=false, C=false;
10         
11         //判断是否有B; 使用索引时要确保索引不越界
12         if(i<s.length() && s.charAt(i)=='.'){
13             i++;
14             B = scanUnsignedInteger(s);
15         }
16         //判断是否有C
17         if(i<s.length() && (s.charAt(i)=='e' || s.charAt(i)=='E')){
18             i++;
19             C = scanInteger(s);
20             //如果存在e|E, 但是没有C, 说明不是数字
21             if(C==false)
22                 return false;
23         }
24         //here, 说明C是合格的, 只需判断A和B的情况
25         //i必须扫描完整个字符串 && (A合格则B合不合格都可以, A不合格则B必须合格)
26         return i==s.length() && (A || B);
27         
28     }
29     
30     private boolean scanInteger(String s){
31         if(i<s.length() && (s.charAt(i)=='+' || s.charAt(i)=='-'))
32             i++;
33         return scanUnsignedInteger(s);
34     }
35     private boolean scanUnsignedInteger(String s){
36         //起始索引
37         int start = i;
38         while(i<s.length() && s.charAt(i)>='0' && s.charAt(i)<='9'){
39             i++;
40         }
41         //i>start说明扫描到了数字; 
42         //i<=start说明没有扫描到数字, 此种情况说明要么start越界, 要么s.charAt(start)不是数字
43         return i > start;
44     }

猜你喜欢

转载自www.cnblogs.com/niliuxiaocheng/p/12592223.html