如何将一个句子分成两个词数相等的组?
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/