简体   繁体   English

如何将句子一分为二?

[英]How to divide sentence into two by two parts?

I have following type of sentences. 我有以下类型的句子。 I want to divide sentence into two by two parts like following example. 我想将句子分为两个部分,例如以下示例。

Example: 例:

Nimal read/write book/newspaper from his pen.

I want to divide following way above sentence and add into arraylist. 我想在句子上方按照以下方式划分并添加到arraylist中。

Nimal/read
Nimal/write
read/book
read/newspaper
write/book
write/newspaper
book/from
newspaper/from
from/his
his/pen.

That's mean I want to get two words phrases from the next word.I have divide and added sentences.But I haven't clear idea to what next to do. 这意味着我想从下一个单词中得到两个单词短语,我已经划分并添加了句子,但是我还不清楚下一步该怎么做。

    ArrayList<String> wordArrayList2 = new ArrayList<String>();
    String sentence="Nimal read/write book/newspaper from his pen";
    for(String wordTw0 : sentence.split(" ")) {
        wordArrayList2.add(wordTw0);
    }

A simple program using String#split() method. 一个使用String#split()方法的简单程序。

steps to follow: 遵循的步骤:

  1. split the whole string based on one or more spaces. 根据一个或多个空格分割整个字符串。
  2. iterate all the strings from the array till length-1. 迭代数组中的所有字符串直到length-1。
  3. get two strings from the array at a time from (i)th and (i+1)th position 从第(i)和(i + 1)个位置一次从数组中获取两个字符串
  4. split both the strings based on forward slash 根据正斜线分割两个字符串
  5. iterate both the array and make words joining then by forward slash 迭代数组并让单词加入,然后用正斜杠
  6. add all the words in the list. 在列表中添加所有单词。

Sample code: 样例代码:

String str = "Nimal read/write book/newspaper from his pen.";

ArrayList<String> wordArrayList = new ArrayList<String>();
String[] array = str.split("\\s+"); // split based on one or more space
for (int i = 0; i < array.length - 1; i++) {
    String s1 = array[i];
    String s2 = array[i + 1];

    String[] a1 = s1.split("/"); //split based on forward slash
    String[] b1 = s2.split("/"); //split based on forward slash
    for (String a : a1) {
        for (String b : b1) {
            String word = a + "/" + b;
            wordArrayList.add(word);
            System.out.println(word);
        }
    }
}

output: 输出:

Nimal/read
Nimal/write
read/book
read/newspaper
write/book
write/newspaper
book/from
newspaper/from
from/his
his/pen.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM