Check if a string contains a number using Java.


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

Updated on: 06-Sep-2023

38K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements