Check if a string contains a number using Java.

Java 8Object Oriented ProgrammingProgramming

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.

Example

Live Demo

public class ContainsExample {
   public static void main(String args[]){
      String sample = "krishna64";
      char[] chars = sample.toCharArray();
      StringBuilder sb = new StringBuilder();
      for(char c : chars){
         if(Character.isDigit(c)){
            sb.append(c);
         }
      }
      System.out.println(sb);
   }
}

Output

64
raja
Published on 12-Feb-2018 07:47:54
Advertisements