【问题标题】:Split sentence by words count in Java在Java中按单词计数拆分句子
【发布时间】:2016-09-19 14:24:55
【问题描述】:

如何将一个句子分成两个字数相等的组?

 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"

我尝试将整个句子拆分为单词,获取第 ((total number of spaces / 2) + 1)th 个空格的索引并应用子字符串。但这很混乱,我无法得到想要的结果。

【问题讨论】:

  • 以下链接可能对您有所帮助。 stackoverflow.com/questions/25853393/…
  • 如果一个句子有奇数个单词会怎样?
  • 应该是 part[0] = even, part[1]=odd,我已经在我的问题中展示了。
  • 你来这里之前有没有尝试过什么?如果是这样,您尝试过什么?那它不起作用怎么办?
  • @amanda014 你是怎么解决你的问题的?

标签: java arrays string


【解决方案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

【讨论】:

  • 是的,它很干净,但我必须使用 Java 7 或更低版本
【解决方案2】:
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;

希望对你有所帮助。

【讨论】:

    【解决方案3】:
    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]
    

    【讨论】:

    • 我认为如果字数甚至在句子中你的代码不能正常工作。
    • 谢谢,我修好了。
    • 我的句子中没有多个空格,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多