我试图确定字符串数组中的特定项是否是整数。
我是.split(" ")'ing中缀表达式的字符串形式,然后尝试将结果数组拆分为两个数组;一个用于整数,一个用于操作符,同时丢弃括号和其他杂项。实现这一目标的最佳方式是什么?
我想我可能能找到一个整数。isInteger(String arg)方法之类的,但没有这样的运气。
我试图确定字符串数组中的特定项是否是整数。
我是.split(" ")'ing中缀表达式的字符串形式,然后尝试将结果数组拆分为两个数组;一个用于整数,一个用于操作符,同时丢弃括号和其他杂项。实现这一目标的最佳方式是什么?
我想我可能能找到一个整数。isInteger(String arg)方法之类的,但没有这样的运气。
当前回答
public boolean isInt(String str){
return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
"\\d+") : str.matches("\\d+");
}
其他回答
你需要使用Integer.parseInt(String)方法。
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
或者简单地
mystring.matches(“\\d+”)
尽管对于大于int型的数字,它会返回true
最好像这样使用正则表达式:
str.matches("-?\\d+");
-? --> negative sign, could have none or one
\\d+ --> one or more digits
如果可以使用if-statement代替,那么在这里使用NumberFormatException是不好的。
如果你不想要前导0,你可以像下面这样使用正则表达式:
str.matches("-?(0|[1-9]\\d*)");
public boolean isInt(String str){
return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
"\\d+") : str.matches("\\d+");
}
或者,您可以从Apache Commons的好朋友StringUtils那里获得一点帮助。isNumeric (String str)