2016-09-18 46 views
2

如何将一个句子分成两组,每个单词的数量相等?按Java计算的单词分词计数

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总数)个空的空间,并应用串。但它很混乱,我无法得到理想的结果。

+0

以下链接可以帮助你。 http://stackoverflow.com/questions/25853393/split-a-string-in-java-into-equal-length-substrings-while-maintaining-word-bound – user6837640

+0

如果一个句子有单数的单词会发生什么? –

+0

它应该像我的问题中显示的part [0] = even,part [1] = odd。 – amanda014

回答

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; 

我希望这可以帮助您。

+0

工作感谢Afsun – amanda014

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] 
+0

我认为如果单词计数甚至在句子中你的代码工作不正常。 –

+0

谢谢,我修好了。 – Kelvin

+0

欢迎您 –

0

使用Java8

在2个测试字符串
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); 

输出很简单的解决方法是:

This is a 
sample sentence 
This is a 
sample sentence two 
+0

是的,它很干净,但我必须使用Java 7或更少 – amanda014