Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split sentence by words count in Java

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.

like image 930
Kushal Avatar asked Jun 17 '26 19:06

Kushal


1 Answers

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
like image 100
Adina-Claudia Toma Avatar answered Jun 19 '26 08:06

Adina-Claudia Toma