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.
The recommended solution is to use the Character. isDigit(char) method to check if the first character of the string is a digit or not.
if(str.matches(".*\\d.*")){ // contains a number } else{ // does not contain a number }
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"));
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"); }
Output
'This string has a 1 number' contains digit 'This string does not have a number' does not contain a digit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With