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

Java实现字符串按3个单词为一组分割的方法

嘿,这个需求其实挺容易实现的,我给你分享几种不同风格的解法,你可以根据自己的场景来选~

方法1:手动遍历分割(最直观,易调试)

这种方法逻辑最清晰,适合新手理解,也方便后续调整分组数量(比如改成按2个或4个单词分组)。核心思路是先把字符串拆成单词数组,再循环每3个一组拼接:

import java.util.ArrayList;
import java.util.List;

public class WordGrouping {
    public static void main(String[] args) {
        String input = "I want to walk in the park with my father";
        List<String> groups = groupWordsByThree(input);
        
        // 打印结果
        groups.forEach(System.out::println);
    }

    public static List<String> groupWordsByThree(String input) {
        List<String> result = new ArrayList<>();
        // 先处理空输入的边界情况
        if (input == null || input.trim().isEmpty()) {
            return result;
        }
        
        // 分割成单词数组,用\\s+匹配任意空白字符(多个空格、制表符都能处理)
        String[] words = input.trim().split("\\s+");
        
        // 每3个单词为一组遍历
        for (int i = 0; i < words.length; i += 3) {
            StringBuilder sb = new StringBuilder();
            // 取当前索引开始的最多3个单词
            int endIndex = Math.min(i + 3, words.length);
            for (int j = i; j < endIndex; j++) {
                if (j > i) {
                    sb.append(" ");
                }
                sb.append(words[j]);
            }
            result.add(sb.toString());
        }
        
        return result;
    }
}

优点:逻辑直白,容易调试,能完美处理最后一组不足3个单词的情况(比如输入末尾只剩1或2个单词也会保留)。

方法2:正则表达式(简洁优雅)

如果追求代码简洁,可以用正则表达式的连续匹配特性,一行核心逻辑就能搞定分组:

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexWordGrouping {
    public static void main(String[] args) {
        String input = "I want to walk in the park with my father";
        List<String> groups = groupWithRegex(input);
        
        groups.forEach(System.out::println);
    }

    public static List<String> groupWithRegex(String input) {
        List<String> result = new ArrayList<>();
        if (input == null || input.trim().isEmpty()) {
            return result;
        }
        
        // 正则说明:\\G保证从上一次匹配结束的位置开始,避免跳过内容;
        // \\S+匹配一个单词,(?:\\s+\\S+){0,2}匹配0-2个(空格+单词),即最多3个单词一组
        Pattern pattern = Pattern.compile("\\G\\S+(?:\\s+\\S+){0,2}");
        Matcher matcher = pattern.matcher(input.trim());
        
        while (matcher.find()) {
            result.add(matcher.group());
        }
        
        return result;
    }
}

优点:代码简洁,不需要手动循环拼接,适合对正则熟悉的开发者。

方法3:Java 8+ Stream API(函数式风格)

如果你的项目用了Java 8及以上版本,用Stream API可以写出更简洁的函数式代码:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class StreamWordGrouping {
    public static void main(String[] args) {
        String input = "I want to walk in the park with my father";
        List<String> groups = groupWithStream(input);
        
        groups.forEach(System.out::println);
    }

    public static List<String> groupWithStream(String input) {
        if (input == null || input.trim().isEmpty()) {
            return List.of();
        }
        
        String[] words = input.trim().split("\\s+");
        
        // 计算分组数:(总单词数 + 2) / 3 是向上取整的写法
        return IntStream.range(0, (words.length + 2) / 3)
                .mapToObj(groupIndex -> {
                    int start = groupIndex * 3;
                    int end = Math.min(start + 3, words.length);
                    // 用String.join拼接指定范围的单词
                    return String.join(" ", java.util.Arrays.copyOfRange(words, start, end));
                })
                .collect(Collectors.toList());
    }
}

优点:符合现代Java的函数式编程风格,代码简洁易读,适合喜欢流式处理的场景。

额外注意点

  • 空白字符处理:用\\s+分割比split(" ")更鲁棒,能处理多个连续空格、制表符、换行符等情况;
  • 边界情况:三种方法都处理了null或空输入的情况,避免抛出异常;
  • 最后一组不足3个:所有方法都会保留最后一组的剩余单词,不会丢弃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:21:20