如何将句子分为两部分?

时间:2014-07-12 08:49:16

标签: java string arraylist split

我有以下类型的句子。我想把句子分为两部分,如下面的例子。

示例:

Nimal read/write book/newspaper from his pen.

我想将以下方式划分为句子并加入arraylist。

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

这意味着我想从下一个单词中得到两个单词短语。我有分词和加句。但我还没有明白接下来要做什么。

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

1 个答案:

答案 0 :(得分:2)

使用String#split()方法的简单程序。

要遵循的步骤:

  1. 根据一个或多个空格拆分整个字符串。
  2. 迭代数组中的所有字符串,直到length-1。
  3. 从(i)和(i + 1)位置
  4. 一次从数组中获取两个字符串
  5. 根据正斜杠
  6. 拆分两个字符串
  7. 迭代数组并通过正斜杠
  8. 使单词加入
  9. 添加列表中的所有单词。
  10. 示例代码:

    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);
            }
        }
    }
    

    输出:

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