gpt4 book ai didi

java - 在 Java 中按字数拆分句子

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

如何将一个句子分成两个词数相等的组?

 Sentence(odd words count) :
This is a sample sentence
Output: part[0] = "This is a "
part[1] = "sample sentence"

Sentence(even words count) :
This is a sample sentence two
Output: part[0] = "This is a "
part[1] = "sample sentence two"

我试图将整个句子拆分成单词,获取第((空格总数/2)+ 1)个空格的索引并应用子字符串。但是它很乱,我无法得到想要的结果。

最佳答案

使用 Java8 的非常简单的解决方案

    String[] splitted = test.split(" ");
int size = splitted.length;
int middle = (size / 2) + (size % 2);
String output1 = Stream.of(splitted).limit(middle).collect(Collectors.joining(" "));
String output2 = Stream.of(splitted).skip(middle).collect(Collectors.joining(" "));
System.out.println(output1);
System.out.println(output2);

2 个测试字符串的输出是:

This is a
sample sentence
This is a
sample sentence two

关于java - 在 Java 中按字数拆分句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39561017/

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