Extract Numbers

Extract all numbers (digits) from a string.

BeginnerTopic: Module 4: String Programs
Back

Java Extract Numbers Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s = sc.nextLine();

        StringBuilder digits = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (Character.isDigit(s.charAt(i))) {
                digits.append(s.charAt(i));
            }
        }
        System.out.println("Digits: " + digits.toString());
        sc.close();
    }
}
Output
Enter a string: a1b23c
Digits: 123

Understanding Extract Numbers

We collect all characters for which Character.isDigit is true.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents