Java program to extract all numbers from a string

Java program to extract numbers from a string :

In this tutorial, we will learn how to extract numbers from a String using Java programming language. The user will enter the string and our program will extract all numbers from the string and print out the result. Let’s take a look at the program first :

Java Program :

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        //1
        Scanner sc = new Scanner(System.in);
        String inputString;

        //2
        System.out.println("Enter a string :");
        inputString = sc.nextLine();

        //3
        System.out.println("Following integers are found in the string : ");

        //4
        for (char ch : inputString.toCharArray()) {
            //5
            if (Character.isDigit(ch)) {
                System.out.print(ch + " ");
            }
        }

    }

}

Explanation :

The commented numbers in the above program denote the step number below :

  1. Create one Scanner object to read user inputs and create one String object to read user input string.

  2. Ask the user to enter a string and store it in the inputString variable.

  3. Print out the integers in the string.

  4. Run one for loop to read character by character. First, convert this string to an array of characters by using the toCharArray() method and then read each character ony by one using a for loop.

  5. Check if the character is a number or not using the isDigit method. If it is a digit, print out the character.

Sample Output :

Enter a string :
hell4 123 lo213 fda21 23
Following integers are found in the string :
4 1 2 3 2 1 3 2 1 2 3

Enter a string :
1 day 2 days 3 days 4 days 5 days
Following integers are found in the string :
1 2 3 4 5

Enter a string :
1 and 2 and 3 and 4 and 5 and 6 and
Following integers are found in the string :
1 2 3 4 5 6

Similar tutorials :