我正在尝试确定字符串数组中的特定项是否为整数.
我是表单中.split(" ")'ing
的中缀表达式String
,然后尝试将结果数组拆分为两个数组; 一个用于整数,一个用于操作符,一个用于丢弃括号和其他杂项.实现这一目标的最佳方法是什么?
我以为我可以找到一种Integer.isInteger(String arg)
方法或东西,但没有这样的运气.
cor*_*iKa 328
最天真的方法是遍历String并确保所有元素都是给定基数的有效数字.这几乎和它可能获得的效率一样高,因为你必须至少查看一次每个元素.我想我们可以根据基数对它进行微观优化,但是对于所有意图和目的来说,这都是你期望获得的.
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 < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以依赖Java库来实现此目的.它不是基于异常的,并且可以捕获您能想到的每个错误情况.它会有点贵(你必须创建一个Scanner对象,它在一个你不想做的非常紧凑的循环中.但它通常不应该太昂贵,所以对于日常操作应该非常可靠.
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();
}
Run Code Online (Sandbox Code Playgroud)
如果最佳实践对您无关紧要,或者您想要对进行代码审查的人进行欺骗,请尝试使用以下内容:
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;
}
Run Code Online (Sandbox Code Playgroud)
shu*_*why 236
使用正则表达式更好.
str.matches("-?\\d+");
-? --> negative sign, could have none or one
\\d+ --> one or more digits
Run Code Online (Sandbox Code Playgroud)
NumberFormatException
如果你可以使用它在这里使用是不好的if-statement
.
如果你不想要前导零,你可以使用正则表达式如下:
str.matches("-?(0|[1-9]\\d*)");
Run Code Online (Sandbox Code Playgroud)
Wil*_*son 134
或者你可以在Apache Commons上向我们的好朋友寻求帮助:StringUtils.isNumeric(String str)
小智 69
或者干脆
mystring.matches("\\d+")
虽然对于大于int的数字它会返回true
Mik*_*wis 53
您想使用Integer.parseInt(String)方法.
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*n C 13
作为尝试解析字符串和捕获的替代方法NumberFormatException
,您可以使用正则表达式; 例如
if (Pattern.compile("-?[0-9]+").matches(str)) {
// its an integer
}
Run Code Online (Sandbox Code Playgroud)
这可能会更快,特别是如果您预编译和重用正则表达式.但是,Integer.parseInt(str)
如果str
代表一个超出合法int
值范围的数字,那么问题仍将是失败.
您可以按以下方式使用Integer.parseInt(str)
并捕获NumberFormatException
if字符串是否为有效整数(如所有答案所指出的):
static boolean isInt(String s)
{
try
{ int i = Integer.parseInt(s); return true; }
catch(NumberFormatException er)
{ return false; }
}
Run Code Online (Sandbox Code Playgroud)
但是,请注意,如果计算的整数溢出,则将抛出相同的异常.你的目的是找出它是否是一个有效的整数.因此,使用自己的方法检查有效性会更安全:
static boolean isInt(String s) // assuming integer is in decimal number system
{
for(int a=0;a<s.length();a++)
{
if(a==0 && s.charAt(a) == '-') continue;
if( !Character.isDigit(s.charAt(a)) ) return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
686880 次 |
最近记录: |