Java 尝试确定字符串是否为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40519580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to determine if a string is an integer
提问by Harry You
Instructions: Given a string, determine if it is an integer. For example the string “123” is an integer, but the string “hello” is not.
说明:给定一个字符串,判断它是否是一个整数。例如,字符串“123”是一个整数,但字符串“hello”不是。
It is an integer if all of the characters in the string are digits.
如果字符串中的所有字符都是数字,则它是一个整数。
Return true if it is an integer, or false if it is not.
如果是整数则返回真,否则返回假。
Hint: There is a method Character.isDigit() that takes a char as an argument and returns a boolean value.
提示:有一个方法 Character.isDigit() 将一个字符作为参数并返回一个布尔值。
What I have so Far:
到目前为止我所拥有的:
public boolean isInteger(String str) {
if(Character.isDigit(str.charAt(0)) == 0) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(Character.isDigit(str.charAt(i))) {
break;
} else {
return false;
}
}
return true;
}
I'm having an issue with returning a boolean value for the string "101" and no string at all (" ")
我在为字符串“101”返回布尔值而根本没有字符串(“”)时遇到问题
回答by OneCricketeer
You could use a regular expression.
您可以使用正则表达式。
return str.matches("\d+");
won't work for negative numbers, though.
但是对负数不起作用。
You could also use Integer.parseInt
and catch the NumberFormatException
and return true/false accordingly.
您还可以使用Integer.parseInt
并捕获NumberFormatException
并相应地返回真/假。
Or, you should not break the first digit you find, as you need to check all characters, only until you find one that is nota digit. Again, this does not capture negative numbers
或者,您不应该打破找到的第一个数字,因为您需要检查所有字符,直到找到不是数字的字符为止。同样,这不会捕获负数
public boolean isInteger(String str) {
if(str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
Personally, option 2 is the best, but your instructions seem to imply that you need to iterate over character values
就个人而言,选项 2 是最好的,但您的说明似乎暗示您需要迭代字符值
回答by riversun
Just check if Integer.parseInt throws exception or not.
只需检查 Integer.parseInt 是否抛出异常。
try {
Integer.parseInt(string);
} catch (NumberFormatException e) {
return false;
}
return true;
回答by hk_csl0615
I suggest using regex to identify integer.
我建议使用正则表达式来识别整数。
Like this
像这样
public boolean isInteger(String str){
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(str);
boolean b = m.matches();
return b;
}
回答by Hypnic Jerk
You are close, but have mixed up logic. I'll go through it with you now.
你很接近,但逻辑混乱。我现在和你一起经历。
if(Character.isDigit(str.charAt(0)) == 0) {
return false;
}
I'm not sure what this above statement if trying to test. I see that you are checking if the After reading your comment it seems that it was meant to check for 0
index is a digit, but then you compare it to 0
. Even if this was written correctly, this statement can be removed because you are about to iterate through the string.null
or empty string. In which case you may want to test the string
directly.
如果尝试测试,我不确定上面的声明是什么。我看到您正在检查阅读您的评论后,它似乎是为了检查0
索引是否为数字,但随后将其与0
. 即使正确编写,也可以删除此语句,因为您将要遍历字符串。null
或空字符串。在这种情况下,您可能希望string
直接测试。
if(str == null || str.isEmpty())
return false;
for (int i = 0; i < str.length(); i++) {
if(Character.isDigit(str.charAt(i))) {
break;
}
else {
return false;
}
}
return true;
The above break;
does not do what I think you think it does. break;
will exit out of the for
loop, thus only checking the first character
. I suggest rewriting this if-else
to get rid of the else
and negate your isDigit
method. See my code below.
以上break;
没有做我认为你认为的那样。break;
将退出for
循环,因此只检查第一个character
. 我建议重写它if-else
以摆脱else
和否定你的isDigit
方法。请参阅下面的我的代码。
for(int i = 0;i < str.length();i++){
if(!Character.isDigit(str.charAt(i))
return false;
}
return true;
You only want to return false
if the character
is not a digit.
return false
如果character
不是数字,您只想要。
回答by kidnan1991
In java, you can use this regex pattern : It will filter either negative or positive value
在 Java 中,您可以使用此正则表达式模式:它将过滤负值或正值
private static final String NUMBER_REGEX = "(^\d++)|(^[\-]{1}\d++)";
private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_REGEX);
final Matcher matcher = NUMBER_PATTERN.matcher(inputString);
if(matcher.find()) {
// If matcher => parse the value
final String sNumber = matcher.group();
final int value = Integer.parseInt(sNumber);
} else {
// Not matching
}
回答by Denis
All the above solution seems correct to me but I would like to give one more solution to this problem. You can check this using ASCII values too:
以上所有解决方案对我来说似乎都是正确的,但我想为这个问题再提供一个解决方案。您也可以使用 ASCII 值进行检查:
private Boolean IsInteger(String str)
{
int length = str.length(),c=0;
if(length==0)
return false;
for(int i=0;i<length; i++)
{
c = (int)str.charAt(i)-48;
if(!(c>=0 && c<10))
return false;
}
return true;
}
I think My solution is much better because it used less number of library functions per iterations.
我认为我的解决方案要好得多,因为它每次迭代使用的库函数数量更少。
I am not checking for negative values because in the questions you have specified that the string is Integer if all the characters are digits. If you want to check negative numbers you can do it by adding one condition in i==0;.
我没有检查负值,因为在您指定的问题中,如果所有字符都是数字,则字符串为 Integer。如果你想检查负数,你可以通过在 i==0; 中添加一个条件来完成。