题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
方法一:
public class Solution {
public boolean
isNumeric(
char[] str) {
try {
Double.parseDouble(
new String(str));
return true;
}
catch(Exception e) {
return false;
}
}
}
方法二:
public class Solution {
public boolean isNumeric(
char[] str) {
return isNumeric(
new String(str));
}
/**
* 题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
*
* @param string
* @return
*/
public static boolean isNumeric(String string) {
if (string ==
null || string.length() <
1) {
return false;
}
int index =
0;
if (string.charAt(index) ==
'+' || string.charAt(index) ==
'-') {
index++;
}
if (index >= string.length()) {
return false;
}
boolean numeric =
true;
index = scanDigits(string, index);
if (index < string.length()) {
if (string.charAt(index) ==
'.') {
index++;
index = scanDigits(string, index);
if (index >= string.length()) {
numeric =
true;
}
else if (index < string.length() && (string.charAt(index) ==
'e' || string.charAt(index) ==
'E')) {
numeric = isExponential(string, index);
}
else {
numeric =
false;
}
}
else if (string.charAt(index) ==
'e' || string.charAt(index) ==
'E') {
numeric = isExponential(string, index);
}
else {
numeric =
false;
}
return numeric;
}
else {
return true;
}
}
/**
* 判断是否是科学计数法的结尾部分,如E5,e5,E+5,e-5,e(E)后面接整数
*
* @param string 字符串
* @param index 开始匹配的位置
* @return 匹配的结果
*/
private static boolean isExponential(String string,
int index) {
if (index >= string.length() || (string.charAt(index) !=
'e' && string.charAt(index) !=
'E')) {
return false;
}
index++;
if (index >= string.length()) {
return false;
}
if (string.charAt(index) ==
'+' || string.charAt(index) ==
'-') {
index++;
}
if (index >= string.length()) {
return false;
}
index = scanDigits(string, index);
return index >= string.length();
}
/**
* 扫描字符串部分的数字部分
*
* @param string 字符串
* @param index 开始扫描的位置
* @return 从扫描位置开始第一个数字字符的位置
*/
private static int scanDigits(String string,
int index) {
while (index < string.length() && string.charAt(index) >=
'0' && string.charAt(index) <=
'9') {
index++;
}
return index;
}
}
方法三:
思路:正则表达式 Java正则表达式的语法与示例
public class Solution {
public boolean
isNumeric(
char[] str) {
String
string = String.valueOf(str);
return string.matches(
"[\\+-]?[0-9]*(\\.[0-9]+)?([eE][\\+-]?[0-9]+)?");
}
}
正则表达式样例:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public static void main(String[] args) {
String str =
"baike.xsoftlab.net";
String regEx =
"baike.";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(str);
boolean rs = matcher.find();
boolean rm = matcher.matches();
System.
out.println(rs);
System.
out.println(rm);
System.
out.println(str.matches(regEx));
}
}