gpt4 book ai didi

java - 将字符串拆分为 3 个单词的部分 Java

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:39 25 4
gpt4 key购买 nike

我想在 Java 中将一个字符串拆分为 3 个单词的一部分。

例如:

I want to walk in the park with my father

我想要一个字符串:"I want to",还有一个字符串:"walk in the",等等

我该怎么做?

最佳答案

这是一个使用 RegEx 的解决方案

String sentence = "I want to walk in the park with my father";

Pattern pattern = Pattern.compile("\\w+ \\w+ \\w+ ");
Matcher matcher = pattern.matcher(sentence);
while (matcher.find()) {
System.out.println(matcher.group());
}

请注意,此表达式的最后一个词“父亲”不匹配。


对于非正则表达式的解决方案,我会使用这样的东西

String sentence = "I want to walk in the park with my father";

String[] words = sentence.split(" ");
List<String> threeWords = new ArrayList<>();

int length = words.length;
for (int ind = 2; ind < length; ind += 3) {
threeWords.add(words[ind - 2] + " " + words[ind - 1] + " " + words[ind]);
}

if (length % 3 == 1) {
threeWords.add(words[length - 1]);
} else if (length % 3 == 2) {
threeWords.add(words[length - 2] + " " + words[length - 1]);
}

关于java - 将字符串拆分为 3 个单词的部分 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com