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

Java拼接字符串数组时如何去除标点符号前的多余空格

问题根因

原代码对所有数组元素统一追加后缀空格,导致单独作为数组元素的标点符号前会被前一个单词的后缀空格填充,同时整句末尾也会多出冗余空格。

修正代码

推荐使用StringBuilder做字符串拼接,通过判断当前元素类型调整空格添加逻辑:

public class Main {
    public static void main(String[] args) {
        String[] words = {"The", "quick", "brown", "fox", ",", "jumps", "over", "the", "lazy", "dog", "."};
        StringBuilder sb = new StringBuilder();
        
        for (int i = 0; i < words.length; i++) {
            String current = words[i];
            // 非首元素且当前元素不是标点时,先加空格再拼接内容
            if (i != 0 && !current.matches("[,.!?;:]")) {
                sb.append(" ");
            }
            sb.append(current);
        }
        
        String result = sb.toString();
        System.out.println(result);
    }
}

运行后输出结果为:The quick brown fox, jumps over the lazy dog.,符合预期。

逻辑说明
  • 替换String直接+=拼接为StringBuilder拼接,避免循环过程生成大量临时字符串,提升执行性能
  • 空格改为前置添加而非后缀添加,从根源避免末尾出现冗余空格
  • 拼接前判断当前元素是否为标点,标点无需添加前置空格,直接和前序内容拼接即可
  • 正则[,.!?;:]可根据实际使用的标点类型扩展,覆盖更多场景即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:57:03