在Java

时间:2016-09-18 18:11:04

标签: java arrays string

如何将一个句子分成两组具有相同数量的单词?

 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)空索引的索引并应用子字符串。但它非常混乱,我无法得到理想的结果。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]

答案 2 :(得分: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;

我希望这对你有所帮助。