表示数值的字符串

 1 package algorithms;
 2 
 3 /**
 4  * 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
 5  * 例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。
 6  * 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
 7  * 
 8  **/
 9 /* 最简便的方法用java的正则表达式去做
10  * 
11  * 数字的格式可以用A[.[B]][E|eC]表示,其中A和C都是整数(可以有符号)
12  * B是无符号整数
13  * */
14 public class IsNumeric {
15     int start = 0;
16 
17     public boolean isNumeric(char[] str) {
18         boolean numeric = false;
19         if (str.length == 0)
20             return false;
21         numeric = scanInteger(str);
22         //如果出现'.',接下类就扫描小数部分
23         if (start < str.length  && str[start] == '.') {
24             start++;
25             //下面一行用 || 的原因
26             //1.小数可以没有数字  但此时必须要有整数部分  如233.
27             //2.小数可以没有整数部分,但此时小数部分必须要有数字 .456
28             //3.正常的小数  233.666
29             numeric = scanUnsignedInteger(str) || numeric;
30         }
31         if (start < str.length-1 && (str[start] == 'e' || str[start] == 'E')) {
32             start++;
33             //e或E前后都要有数字  所以用&&
34             numeric = scanInteger(str) && numeric;
35         }
36         return numeric && (start == str.length);
37     }
38 
39     public boolean scanUnsignedInteger(char[] str) {
40         int i;
41         for (i = start; i < str.length; i++) {
42             if (!(str[i] >= '0' && str[i] <= '9'))
43                 break;
44         }
45         if (i > start) {
46             start = i ;
47             return true;
48         }
49         return false;
50     }
51 
52     public boolean scanInteger(char[] str) {
53         if (str[start] == '+' || str[start] == '-') {
54             start++;
55             return scanUnsignedInteger(str);
56         }
57         return scanUnsignedInteger(str);
58     }
59 
60     public static void main(String[] args) {
61         char[] str = { '1', '2', '3','.','4','5','e','+','6' };
62         IsNumeric ma = new IsNumeric();
63         System.out.println(ma.isNumeric(str));
64     }
65 }
原文地址:https://www.cnblogs.com/ustc-anmin/p/10619489.html