Java 如何判断一个字符串是否包含一个整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4388546/
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
How to determine whether a string contains an integer?
提问by Nick
Say you have a string that you want to test to make sure that it contains an integer before you proceed with other the rest of the code. What would you use, in java, to find out whether or not it is an integer?
假设您要测试一个字符串以确保它包含一个整数,然后再继续执行其他代码。在java中,你会用什么来确定它是否是一个整数?
采纳答案by Jonathon Bolster
If you want to make sure that it is onlyan integer and convert it to one, I would use parseIntin a try/catch
. However, if you want to check if the string contains a number then you would be better to use the String.matcheswith Regular Expressions: stringVariable.matches("\\d")
如果你想确保它是唯一的整数,并将其转换为一个,我会用parseInt函数中try/catch
。但是,如果您想检查字符串是否包含数字,那么最好将String.matches与正则表达式一起使用:stringVariable.matches("\\d")
回答by Freddie
Use the method Integer.parseInt() at http://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html
使用http://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html 上的Integer.parseInt() 方法
回答by AlexR
User regular expression:
Pattern.compile("^\\s*\\d+\\s*$").matcher(myString).find();
Just wrap Integer.parse() by try/catch(NumberFormatException)
用户正则表达式:
Pattern.compile("^\\s*\\d+\\s*$").matcher(myString).find();
只需通过 try/catch(NumberFormatException) 包装 Integer.parse()
回答by dimitrisli
You can check whether the following is true: "yourStringHere".matches("\\d+")
您可以检查以下是否正确: "yourStringHere".matches("\\d+")
回答by user489041
String s = "abc123";
for(char c : s.toCharArray()) {
if(Character.isDigit(c)) {
return true;
}
}
return false;
回答by Andreas Dolk
If you just want to test, if a String contains an integer value only, write a method like this:
如果你只是想测试,如果一个字符串只包含一个整数值,写一个这样的方法:
public boolean isInteger(String s) {
boolean result = false;
try {
Integer.parseInt("-1234");
result = true;
} catch (NumberFormatException nfe) {
// no need to handle the exception
}
return result;
}
parseInt
will return the int
value (-1234 in this example) or throw an exception.
parseInt
将返回int
值(在此示例中为 -1234)或引发异常。
回答by CoolBeans
You can use apache StringUtils.isNumeric.
您可以使用 apache StringUtils.isNumeric。
回答by Pau
You might also want to have a look at java.util.Scanner
您可能还想看看java.util.Scanner
Example:
例子:
new Scanner("456").nextInt
回答by Jon
int number = 0;
try {
number = Integer.parseInt(string);
}
catch(NumberFormatException e) {}
回答by kirchhoff
I use the method matches() from the String class:
我使用 String 类中的matches()方法:
Scanner input = new Scanner(System.in)
String lectura;
int number;
lectura = input.next();
if(lectura.matches("[0-3]")){
number = lectura;
}
This way you can also validate that the range of the numbers is correct.
通过这种方式,您还可以验证数字范围是否正确。