在解析字符串之前,如何检查它是否是一个数字?
当前回答
我们可以尝试用("")即空格替换给定字符串中的所有数字,如果在此之后字符串的长度为零,那么我们可以说给定字符串只包含数字。 例子:
boolean isNumber(String str){
if(str.length() == 0)
return false; //To check if string is empty
if(str.charAt(0) == '-')
str = str.replaceFirst("-","");// for handling -ve numbers
System.out.println(str);
str = str.replaceFirst("\\.",""); //to check if it contains more than one decimal points
if(str.length() == 0)
return false; // to check if it is empty string after removing -ve sign and decimal point
System.out.println(str);
return str.replaceAll("[0-9]","").length() == 0;
}
其他回答
正则表达式匹配
这里是另一个例子升级了“CraigTP”正则表达式匹配更多的验证。
public static boolean isNumeric(String str)
{
return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
}
只有一个负号——允许且必须在开头。 负号后面必须有数字。 只有一个小数符号。允许的。 小数点后必须有数字。
正则表达式测试
1 -- **VALID**
1. -- INVALID
1.. -- INVALID
1.1 -- **VALID**
1.1.1 -- INVALID
-1 -- **VALID**
--1 -- INVALID
-1. -- INVALID
-1.1 -- **VALID**
-1.1.1 -- INVALID
异常开销很大,但在这种情况下,RegEx需要更长的时间。下面的代码显示了两个函数的简单测试——一个使用异常,一个使用正则表达式。在我的机器上,RegEx版本比异常慢10倍。
import java.util.Date;
public class IsNumeric {
public static boolean isNumericOne(String s) {
return s.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
public static boolean isNumericTwo(String s) {
try {
Double.parseDouble(s);
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String [] args) {
String test = "12345.F";
long before = new Date().getTime();
for(int x=0;x<1000000;++x) {
//isNumericTwo(test);
isNumericOne(test);
}
long after = new Date().getTime();
System.out.println(after-before);
}
}
这通常是通过一个简单的用户定义函数来完成的(例如,roll your-own的“isNumeric”函数)。
喜欢的东西:
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
然而,如果您经常调用这个函数,并且由于不是一个数字,您希望许多检查失败,那么这种机制的性能就不会很好,因为您依赖于每次失败都会抛出异常,这是一个相当昂贵的操作。
另一种方法可能是使用正则表达式来检查是否是一个数字:
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
但是要小心上面的RegEx机制,因为如果你使用非阿拉伯数字(即0到9以外的数字),它会失败。这是因为RegEx的“\d”部分只匹配[0-9],并且有效地不具有国际数字意识。(感谢OregonGhost指出这一点!)
甚至另一种替代方法是使用Java内置的Java .text. numberformat对象来查看解析字符串后解析器的位置是否位于字符串的末尾。如果是,我们可以假设整个字符串都是数字:
public static boolean isNumeric(String str) {
ParsePosition pos = new ParsePosition(0);
NumberFormat.getInstance().parse(str, pos);
return str.length() == pos.getIndex();
}
在Apache Commons Lang 3.5及以上版本中:NumberUtils。isCreatable或StringUtils.isNumeric。
使用Apache Commons Lang 3.4及以下版本:NumberUtils。isNumber或StringUtils.isNumeric。
你也可以使用StringUtils。isNumericSpace对于空字符串返回true,忽略字符串中的内部空格。另一种方法是使用NumberUtils。isParsable,根据Java检查数字是否可解析。(链接的javadocs包含每种方法的详细示例。)
import java.util.Scanner;
public class TestDemo {
public static void main(String[] args) {
boolean flag = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) > 48 && str.charAt(i) < 58) {
flag = false;
break;
}
}
if(flag == true) {
System.out.println("String is a valid String.");
} else {
System.out.println("String contains number.");
}
}
}
推荐文章
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 如何删除表中特定列的第一个字符?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 如何在POM.xml中引用环境变量?
- 如何在android中复制一个文件?
- 将整数转换为字符串,以逗号表示千
- 将JavaScript字符串中的多个空格替换为单个空格
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- printf()和puts()在C语言中的区别是什么?