คลาส java.lang.String ให้เมธอดมากมายสำหรับจัดการ string ด้วยเมธอดเหล่านี้ สามารถทำ operations บน string ได้ เช่น trimming, concatenating, converting และ comparing เราสามารถดึงตัวเลขจาก string ที่กำหนดได้โดยใช้เมธอด replaceAll() ของคลาส String
ตัวอย่าง
import java.util.Scanner;
public class StringExtractTest {
public static void main(String[] args) {
String input;
String numbers;
Scanner scanner = new Scanner(System.in);
System.out.print(" Please enter a string from the keyboard that contains numbers: ");
input = scanner.nextLine();
numbers = input.replaceAll("[^0-9]", "");
System.out.println("The Numbers are: " + numbers);
}
}
Output
Please enter a string from the keyboard that contains numbers: Welcome to Tutorials Point 1234567890 The Numbers are: 1234567890