如何从句子中组合组合

时间:2015-04-30 17:06:38

标签: java

我试图从一个原始句子中产生array个句子,但也保留顺序

例如

"The amazing spider man returns" 

会产生5个句子

"The" 
"The amazing" 
"The amazing spider" 
"The amazing spider man" 
"The amazing spider man returns" 

我开始循环,但我无法弄清楚如何去做它

        String[] words=title.split(" ");
        for (int i = 0; i < words.length; i++) {

        ???
        } 

2 个答案:

答案 0 :(得分:3)

我认为你可以这样做:

    String[] words=title.split(" ");
    String printWord = "";
    for (int i = 0; i < words.length; i++) {
        printWord += words[i] + " "; // Add the space for newly appended words
        System.out.println(printWord);
    }

以上,只会打印以下内容

The 
The amazing 
The amazing spider 
The amazing spider man 
The amazing spider man returns 

如果您想存储它,只需将其添加到新数组,而不是调用System.out.println()

编辑:删除了返回字符串中的引号,因为它不打印引号,当然:P

Edit2:如果你想将它添加到没有尾随空格的数组中,只需在添加到数组时使用String.trim()

答案 1 :(得分:3)

你可以做到

String title = "The amazing spider man returns";
String[] words = title.split(" ");
String[] result = new String[words.length];

for (int i = 0; i < words.length; i++) {

    if (i == 0) 
       result[i] = words[i];
    else 
       result[i] = result[i - 1] + " " + words[i];

}
System.out.println(Arrays.toString(result));

输出

[The, The amazing, The amazing spider, The amazing spider man, The amazing spider man returns]

Demo