You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java移除字符串多余分隔符 输入日期输出空白问题如何解决

问题根因

  • 核心错误是for循环判断条件写反:你写的循环条件为i > words.length,i初始值是0,你输入25-06-2008经过split("\\D")分割后得到的数组长度是3,0永远不可能大于3,因此循环体一次都不会执行,拼接用的变量oo始终是空字符串,最终输出自然为空白。
  • 次要注意点:你当前分割后拼接的顺序是「日-月-年」,后续转LocalDate时需要匹配对应的格式,否则会出现解析报错。

修复后代码

import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Test {
    public static void main(String[] args) {
        Scanner darshit = new Scanner(System.in);
        String oo = "";
        System.out.println("Enter your DOB: ");
        String dob = darshit.next();
        String[] words = dob.split("\\D");
        // 修正循环判断条件
        for (int i = 0; i < words.length; i++) {
            oo = oo + words[i];
        }
        System.out.println(oo);
        // 后续转LocalDate示例
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("ddMMyyyy");
        LocalDate localDate = LocalDate.parse(oo, dtf);
        System.out.println("解析后的日期对象:" + localDate);
        darshit.close();
    }
}

更简化的实现方案

不需要分割再循环拼接,直接用正则替换所有非数字字符即可,一行代码就能得到纯数字字符串:

String oo = dob.replaceAll("\\D", "");

内容的提问来源于stack exchange,提问作者Darshit ff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 13:45:03