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

使用replaceAll去除空格并通过toCharArray拆分字符串失效问题

问题分析与解决

嘿,我一眼就瞅出问题出在哪了!你的replaceAll("\\s+","")方法本身没毛病,真正的问题在于你用了scanner.next()来读取输入。

为啥会这样?

Scanner.next()方法的默认行为是:以空格、制表符、换行符这类空白字符作为分隔符,只读取到第一个空白字符为止。也就是说,当你输入I am entering some word.时,word变量其实只拿到了第一个单词"I",后面的" am entering some word."根本没被读进程序里,那replaceAll当然没法处理那些空格啦!

怎么修复?

把scanner.next()换成scanner.nextLine()就行,这个方法会读取整行输入(包括所有空格),直到遇到换行符为止。修改后的代码如下:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word: ");
        // 换成nextLine读取整行输入
        String word = scanner.nextLine();
        String cleansed = word.replaceAll("\\s+","");
        char[] letters = cleansed.toCharArray();
        for(char c : letters){
            System.out.print(c+" ");
        }
        scanner.close();
    }
}

测试效果

当你输入I am entering some word.时,cleansed会变成"Iamenteringsomeword.",最终输出就是:

I a m e n t e r i n g s o m e w o r d . 

完全符合你的预期啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:32:13