一、题目
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
例子说明
例如,字符串“+100”,“5e2”,“-123”,“3.1416”及”-1E-16”都表示数值,但“12e”,”1a3.14”,”1.2.3”,”±5”及“12e+5.4”都不是。
二、解题思路
原文链接:https://blog.csdn.net/weixin_38108266/article/details/82749396
分析:
判断字符串是否是数字,首先这个字符串必须只包括以下几种情况:
1)0—9之间的数字
2)e或者E,指数,不能在末尾,e后面如果有+ - 号,则正负号后面不能有小数点。比如 12e+4.3
3)+ - 表示正负,不能在末尾出现,正负号如果在中间,那么前一个是e或者E,后一个是0—9的数字 比如 -1e-16
4). 小数点只能有一个 比如 1.2.3
public static void main(String[] args) {
test1();
}
public static void test1() {
char[] str = null;
test("test1", str, false);
char[] str2 = {};
test("test2", str2, false);
String string = "e3";
char[] str3 = string.toCharArray();
test("test3", str3, false);
String string1 = "3e1.2";
char[] str4 = string1.toCharArray();
test("test4", str4, false);
String string5 = "1.2e3";
char[] str5 = string5.toCharArray();
test("test5", str5, true);
String string6 = "-.2e3";
char[] str6 = string6.toCharArray();
test("test6", str6, true);
String string8 = "-.2e-3";
char[] str8 = string8.toCharArray();
test("test8", str8, true);
String string9 = "1.e-3";
char[] str9 = string9.toCharArray();
test("test9", str9, true);
String string10 = "1.";
char[] str10 = string10.toCharArray();
test("test10", str10, true);
String string11 = ".2";
char[] str11 = string11.toCharArray();
test("test11", str11, true);
String string12 = "12e3";
char[] str12 = string12.toCharArray();
test("test12", str12, true);
}
public static void test(String testName, char[] str, boolean expected) {
System.out.print(testName + ":");
if (isNumeric(str) == expected)
System.out.println(" passed!");
else
System.out.println(" failed!");
}
/**
* 数字的基本格式为:(A.B E/e A) ,按顺序进行判断
* A代表带符号整数,B代表不带符号整数
* 小心:时刻要注意数组越界问题!
*
* @param str
* @return
*/
public static boolean isNumeric(char[] str) {
if (str == null || str.length == 0) {
return false;
}
int[] intdex = new int[1];
intdex[0] = 0; // 用于记录当前字符位置
// 先判断A
boolean isNumeric; //用于记录是否满足条件
isNumeric = isInteger(str, intdex);
// 判断B
if (intdex[0] < str.length && (str[intdex[0]] == '.')) {
intdex[0]++;
isNumeric = isUnsignedInteger(str, intdex) || isNumeric;
}
// 判断e后面的A
if (intdex[0] < str.length && (str[intdex[0]] == 'e' || str[intdex[0]] == 'E')) {
intdex[0]++;
isNumeric = isInteger(str, intdex) && isNumeric;
}
if (intdex[0] == str.length && isNumeric) {
return true;
}
return false;
}
/**
* // 用int[]才能传值,int的话需要定义index为全局变量
*
* @param str
* @param index
* @return
*/
private static boolean isInteger(char[] str, int[] index) {
if (index[0] < str.length && (str[index[0]] == '+' || str[index[0]] == '-')) {
index[0]++;
}
return isUnsignedInteger(str, index);
}
private static boolean isUnsignedInteger(char[] str, int[] index) {
int start = index[0];
while (index[0] < str.length && (str[index[0]] - '0' <= 9 && str[index[0]] - '0' >= 0)) {
index[0]++;
}
if (index[0] > start) {
return true;
} else {
return false;
}
}