How can I split a sentence into two groups with equal number of words?
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"
I tried to split the whole sentence into words, getting the index of ((total number of spaces / 2) + 1)th empty space and apply substring. But it is quite messy and I was unable to get the desired result.
Pretty simple solution using 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);
Output on the 2 test strings is:
This is a
sample sentence
This is a
sample sentence two
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With