如何编写一个方法来查找给定字符串是否包含数字?如果字符串包含数字,则该方法应返回 true,否则返回 false。
最佳答案
if(str.matches(".*\\d.*")){
// contains a number
} else{
// does not contain a number
}
以前建议的解决方案,不起作用,但由于@Eng.Fouad 的请求/建议而恢复。
建议的解决方案不起作用
String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string does not have a number";
System.out.println(strWithNumber.contains("\d"));
System.out.println(strWithoutNumber.contains("\d"));
工作解决方案
String strWithNumber = "This string has a 1 number";
if(strWithNumber.matches(".*\\d.*")){
System.out.println("'"+strWithNumber+"' contains digit");
} else{
System.out.println("'"+strWithNumber+"' does not contain a digit");
}
String strWithoutNumber = "This string does not have a number";
if(strWithoutNumber.matches(".*\\d.*")){
System.out.println("'"+strWithoutNumber+"' contains digit");
} else{
System.out.println("'"+strWithoutNumber+"' does not contain a digit");
}
输出
'This string has a 1 number' contains digit
'This string does not have a number' does not contain a digit
关于java - 检查字符串是否包含Java中的数字值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6344867/