检查String是否包含Java中的数字值 [英] Checking whether a String contains a number value in Java

查看:103
本文介绍了检查String是否包含Java中的数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写方法来查找给定字符串是否包含数字?如果字符串包含数字,则该方法应返回true,否则返回false。

How can I write a method to find whether a given string contains a number? The method should return true if the string contains a number and false otherwise.

推荐答案

if(str.matches(".*\\d.*")){
   // contains a number
} else{
   // does not contain a number
}

以前建议的解决方案,但不起作用,但由于@ Eng.Fouad的请求而被带回建议。

Previous suggested solution, which does not work, but brought back because of @Eng.Fouad's request/suggestion.

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"));



工作解决方案



Working solution

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

这篇关于检查String是否包含Java中的数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆