如何从输入中去除空格并提取最后一个数字?
问题描述
- 需求:从输入文本中去除空格,并提取其中的最后一个数字(例如输入中的1、2、6这类数字)
- 已尝试代码:
String line = scanner.nextLine(); String[] parts = line.split(" "); int ProductCount =Integer.parseInt(parts[3].replaceAll(" ", ""));
现有代码的问题
这段代码通过按空格分割字符串并固定取索引3的元素来提取数字,严重依赖输入的固定格式——如果数字位置变化、空格数量不一致,就会直接报错,无法稳定提取最后一个数字。
解决方案
方法1:正则表达式匹配(推荐)
用正则可以精准定位最后一个数字,同时先去除所有空格,适配各种输入格式:
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); // 去除所有空白字符(空格、制表符等) String cleanedLine = line.replaceAll("\\s", ""); // 匹配最后一个连续数字序列(支持多位数,如123) Pattern pattern = Pattern.compile("(\\d+)(?!.*\\d)"); Matcher matcher = pattern.matcher(cleanedLine); if (matcher.find()) { int productCount = Integer.parseInt(matcher.group(1)); System.out.println("提取到的最后一个数字:" + productCount); } else { System.out.println("输入中未找到数字"); } } }
- 关键说明:
replaceAll("\\s", ""):一次性清除所有空白字符,避免空格干扰数字提取- 正则
(\\d+)(?!.*\\d):\\d+匹配一个或多个数字,(?!.*\\d)确保后面没有其他数字,精准锁定最后一个数字序列
方法2:从末尾向前遍历查找
不想用正则的话,可以直接从字符串末尾反向遍历,收集连续数字:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); // 去除所有空格 String cleanedLine = line.replaceAll("\\s", ""); StringBuilder lastNumBuilder = new StringBuilder(); // 从字符串最后一位开始向前遍历 for (int i = cleanedLine.length() - 1; i >= 0; i--) { char c = cleanedLine.charAt(i); if (Character.isDigit(c)) { lastNumBuilder.append(c); } else { // 遇到非数字字符,停止遍历 break; } } if (lastNumBuilder.length() > 0) { // 反转字符串得到正确顺序的数字,再转为整数 int productCount = Integer.parseInt(lastNumBuilder.reverse().toString()); System.out.println("提取到的最后一个数字:" + productCount); } else { System.out.println("输入中未找到数字"); } } }
- 关键说明:
- 先清除所有空格,再从后往前收集数字字符,最后反转得到正确的数字顺序,避免遗漏多位数
内容的提问来源于stack exchange,提问作者Codrunnr
相关产品推荐
相关产品推荐

