3

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.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
Kushal
  • 98
  • 12

3 Answers3

2

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
0
String sentence = "This is a sample sentence";

String[] words = sentence.split(" +"); // Split words by spaces
int count = (int) ((words.length / 2.0) + 0.5); // Number of words in part[0]
String[] part = new String[2];
Arrays.fill(part, ""); // Initialize to empty strings
for (int i = 0; i < words.length; i++) {
    if (i < count) { // First half of the words go into part[0]
        part[0] += words[i] + " ";
    } else { // Next half go into part[1]
        part[1] += words[i] + " ";
    }
}
part[1] = part[1].trim(); // Since there will be extra space at end of part[1]
Kelvin
  • 574
  • 3
  • 13
0
String sentence ="This is a simple sentence";
String[] words = sentence.split(" ");

double arrayCount=2;
double firstSentenceLength = Math.ceil(words.length/arrayCount);
String[] sentences = new String[arrayCount];
String first="";
String second="";

for(int i=0; i < words.length; i++){
      if(i<firstSentenceLength){
          first+=words[i]+ " ";
      }else{
          second+=words[i]+ " ";
      }
}
sentences[0]=first;
sentences[1]=second;

I hope this help you.

Afsun Khammadli
  • 2,048
  • 4
  • 18
  • 28