我怎样才能把一个句子分成"He and his brother playing football."
几个部分,如"He and"
,、和。是否可以通过使用Java来做到这一点?"and his"
"his brother"
"brother playing"
"playing football"
问问题
15622 次
4 回答
7
假设“单词”总是由一个空格分隔。采用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]);
于 2012-06-19T05:53:36.447 回答
4
您可以使用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();
}
于 2012-06-19T06:04:55.643 回答
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]);
}
于 2012-06-19T05:56:02.580 回答
0
使用 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);
}
}
应该打印出来:
沙
卖
贝壳
经过
这
海
支撑。
可能是也可能不是你所追求的。
于 2012-06-19T06:01:29.630 回答