如何查找字符串是否包含整数?
假设您有一个要测试的字符串,以确保它在继续其他代码之前包含一个整数。 在java中,您将使用什么来查明它是否是整数?
如果你想确保它只是一个整数并将其转换为1,我会在try/catch
使用parseInt 。 但是,如果要检查字符串是否包含数字,那么最好使用带正则表达式的String.matches : stringVariable.matches("\\d")
String s = "abc123"; for(char c : s.toCharArray()) { if(Character.isDigit(c)) { return true; } } return false;
您可以检查以下内容是否为真: "yourStringHere".matches("\\d+")
我使用String类中的方法matches():
Scanner input = new Scanner(System.in) String lectura; int number; lectura = input.next(); if(lectura.matches("[0-3]")){ number = lectura; }
这样,您还可以validation数字的范围是否正确。
-
用户正则表达式:
Pattern.compile("^\\s*\\d+\\s*$").matcher(myString).find();
-
只需通过try / catch(NumberFormatException)包装Integer.parse()
您可能还想查看java.util.Scanner
例:
new Scanner("456").nextInt
你可以随时使用Googles Guava
String text = "13567"; CharMatcher charMatcher = CharMatcher.DIGIT; int output = charMatcher.countIn(text);
这应该工作:
public static boolean isInteger(String p_str) { if (p_str == null) return false; else return p_str.matches("^\\d*$"); }
如果您只想测试,如果String只包含整数值,请编写如下方法:
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
将返回int
值(在此示例中为-1234)或抛出exception。
int number = 0; try { number = Integer.parseInt(string); } catch(NumberFormatException e) {}
您可以使用apache StringUtils.isNumeric 。
使用http://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html上的 Integer.parseInt()方法