我们如何从Java中的输入字符串中提取数字?
该java.lang.String中 类提供的方法有相当的措施来处理字符串。借助这些方法,您可以对字符串执行诸如修整,连接,转换和比较之类的操作。我们可以使用String 类的replaceAll() 方法从给定的字符串中提取数字。
示例
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); } }
输出结果
Please enter a string from the keyboard that contains numbers: Welcome to nhooo.com 1234567890The Numbers are: 1234567890