本文翻译自:Determine if a String is an Integer in Java [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
I'm trying to determine if a particular item in an Array of strings is an integer or not. 我正在尝试确定字符串数组中的特定项目是否为整数。
I am .split(" ")'ing
an infix expression in String
form, and then trying to split the resultant array into two arrays; 我.split(" ")'ing
以String
形式插入一个中缀表达式,然后尝试将结果数组拆分为两个数组; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. 一个用于整数,一个用于运算符,同时丢弃括号和其他杂项。 What would be the best way to accomplish this? 做到这一点的最佳方法是什么?
I thought I might be able to find a Integer.isInteger(String arg)
method or something, but no such luck. 我以为我可以找到Integer.isInteger(String arg)
方法或其他方法,但是没有这种运气。
#1楼
参考:https://stackoom.com/question/mP4l/确定字符串是否是Java中的整数-重复
#2楼
Or simply 或者简单地
mystring.matches("\\\\d+")
though it would return true for numbers larger than an int 尽管对于大于int的数字将返回true
#3楼
Using regular expression is better. 使用正则表达式更好。
str.matches("-?\\d+");
-? --> negative sign, could have none or one
\\d+ --> one or more digits
It is not good to use NumberFormatException
here if you can use if-statement
instead. 如果可以改为使用if-statement
在此处使用NumberFormatException
不好。
If you don't want leading zero's, you can just use the regular expression as follow: 如果您不想以零开头,则可以使用正则表达式,如下所示:
str.matches("-?(0|[1-9]\\d*)");
#4楼
public boolean isInt(String str){
return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
"\\d+") : str.matches("\\d+");
}
#5楼
You want to use the Integer.parseInt(String) method. 您要使用Integer.parseInt(String)方法。
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
#6楼
You can use Integer.parseInt()
or Integer.valueOf()
to get the integer from the string, and catch the exception if it is not a parsable int. 您可以使用Integer.parseInt()
或Integer.valueOf()
从字符串中获取整数,如果它不是可解析的int,则捕获该异常。 You want to be sure to catch the NumberFormatException
it can throw. 您要确保捕获到它可能引发的NumberFormatException
。
It may be helpful to note that valueOf() will return an Integer object, not the primitive int. 注意valueOf()将返回一个Integer对象,而不是原始int可能会有所帮助。