-->

如何把一个句子分成部分的Java?(How to divide a sentence into pa

2019-09-18 05:40发布

我怎么可以把喜欢的一句话"He and his brother playing football." 到像几个部分"He and""and his""his brother""brother playing""playing football" 。 是否有可能做到这一点通过使用Java?

Answer 1:

假设“字”总是由一个单一的空间分离。 使用String.split()

String[] words = "He and his brother playing football.".split("\\s+");
for (int i = 0, l = words.length; i + 1 < l; i++)
        System.out.println(words[i] + " " + words[i + 1]);


Answer 2:

您可以使用的BreakIterator类和它的静态方法getSentenceInstance()做到这一点Returns a new BreakIterator instance for sentence breaks for the default locale

You can also use getWordInstance(), getLineInstance().. to break words, line...etc

例如:

BreakIterator boundary = BreakIterator.getSentenceInstance();

boundary.setText("Your_Sentence");

int start = boundary.first();

int end = boundary.next();

Iterate over it... to get the Sentences....

欲了解更多详细看看这个链接:

http://docs.oracle.com/javase/6/docs/api/java/text/BreakIterator.html

编辑答案This is a working code

String sent = "My name is vivek. I work in TaxSmart";
        BreakIterator bi = BreakIterator.getSentenceInstance();
        bi.setText(sent);
        int index = 0;
        while (bi.next() != BreakIterator.DONE) {
        String sentence = sent.substring(index, bi.current());
        System.out.println("Sentence: " + sentence);
        index = bi.current();
        }


Answer 3:

String str="He and his brother playing football";

    String [] strArray=str.split(" ");
    for(int i=0;i<strArray.length-1 ;i++)
    {
        System.out.println(strArray[i]+" "+strArray[i+1]);
    }


Answer 4:

使用的StringTokenizer以空格或其他字符分隔。

import java.util.StringTokenizer;

public class Test {

         private static String[] tokenize(String str) {
            StringTokenizer tokenizer = new StringTokenizer(str);
        String[] arr = new String[tokenizer.countTokens()];
        int i = 0;
        while (tokenizer.hasMoreTokens()) {
        arr[i++] = tokenizer.nextToken();
        }
        return arr;
     }

    public static void main(String[] args) {
        String[] strs = tokenize("Sandy sells seashells by the sea shore.");
        for (String s : strs)
            System.out.println(s);
    }
}

如果打印出来:

塞尔斯

贝壳

通过

岸。

可能会或可能不会是你追求的。



文章来源: How to divide a sentence into parts Java?