作者:牛牛的牛66_674 | 来源:互联网 | 2023-01-29 13:06
This question already has an answer here:
这个问题已经有了答案:
- What's the best way to check if a String represents an integer in Java? 34 answers
- 检查字符串是否表示Java中的整数的最好方法是什么?34个答案
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; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. What would be the best way to accomplish this?
我是。split(“”)将一个infix表达式用字符串形式表示,然后尝试将结果数组拆分为两个数组;一个用于整数,一个用于运算符,同时丢弃圆括号和其他杂项。最好的方法是什么?
I thought I might be able to find a Integer.isInteger(String arg)
method or something, but no such luck.
我想我可以找到一个整数。isInteger(String arg)方法或什么的,但没有这样的运气。
9 个解决方案
297
The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.
最简单的方法是遍历字符串,并确保所有元素都是给定基数的有效数字。这是尽可能有效的,因为您必须至少查看每个元素一次。我想我们可以基于基数对它进行微优化,但是对于所有的意图和目的,这是你可以期望得到的。
public static boolean isInteger(String s) {
return isInteger(s,10);
}
public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i
Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.
或者,您可以依赖Java库来实现这一点。它并不是特例,它将捕获您所能想到的所有错误条件。它将会更贵一些(你必须创建一个扫描对象,在一个你不想做的临界循环中)。但它一般不应该太贵,所以对于日常运营来说,它应该是相当可靠的。
public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix)) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt(radix);
return !sc.hasNext();
}
If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:
如果最佳实践对您来说不重要,或者您想要对您进行代码评审的人,请尝试以下的大小:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}