Extract Numbers in Java

Extract all numbers (digits) from a string.

BeginnerModule 4: String ProgramsExample 19 of 25
extract-numbers.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a string: ");
7 String s = sc.nextLine();
8
9 StringBuilder digits = new StringBuilder();
10 for (int i = 0; i < s.length(); i++) {
11 if (Character.isDigit(s.charAt(i))) {
12 digits.append(s.charAt(i));
13 }
14 }
15 System.out.println("Digits: " + digits.toString());
16 sc.close();
17 }
18}

Output

Enter a string: a1b23c
Digits: 123

What's going on

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