2011-06-08 390 views
0

问候所有;当在Java中找到某个单词时将长句分割成短句

我有一个String类型的LinkedList,其中包含一些词,如[from,to,in,then,然而] ,我有一个包含长句子的文本文件。 我想要做的是当发现上述单词之一时,用较短的句子分割这些句子。

到目前为止,我做了一个包含单词的链表,以及另一个包含文件中长句子的链表。 我不知道如何分割长句?

我已经试过这样:

int indexofsw = 0; 
     for (int k = 0; k < LongSentence.size(); k++) { 
       for (int j = 0; j < SWords.size(); j++) { 
        if (LongSentence.get(k).contains(SWords.get(j))== true) { 
         indexofsw = LongSentence.get(k).indexOf(SWords.get(j)); 
         System.out.println(LongSentence.get(k).substring(k,indexofsw)); 
         break; 

        } 
       } 
      } 

但它不会返回一个短句子。

有什么想法吗?

+0

字符串确实有['split'](http://download.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29)方法。 – mre 2011-06-08 14:59:26

回答

1

test.java,让你开始:

public class test{ 
    public static void main(String[] args){ 
    String[] splitWords = {"to", "in", "from", "then"}; 
    String str = "this from that"; 
    String[] tmp; 
    for (String splitTkn : splitWords){ 
     tmp = str.split(splitTkn); 
     if (tmp.length > 1){ 
     System.out.println(tmp[0].trim()); 
     System.out.println(tmp[1].trim()); 
     } 
    } 
    } 
} 

输出:

this 
that 
+0

如果我想遍历所有的单词列表[从,到,然后,然而,但是]我已经尝试过,但它给出了一个exeption'String [] temp = null; (int j = 0; j Daisy 2011-06-08 19:19:17

+0

我编辑了这个例子,看看是否有帮助。 – 2011-06-08 20:09:45

0

你的意思是?

Set<String> wordsToRemove = 
String sentence = 
List<String> words = Arrays.asList(sentence.split(" ")); 
words.removeAll(wordsToRemove); 
+0

谢谢你的回复,但我的意思是分割列表中的每个单词而不是空间。 – Daisy 2011-06-09 13:42:20

0

尝试使用替代:

public class test { 
    public static void main(String[] args){ 
    String[] splitWords = {"to", "in", "from", "then"}; 
    String string = "this from that"; 
    for (String splitWord : splitWords) { 
     string = string.replace(" " + splitWord + " ", System.getProperty("line.separator")); 
    } 
    System.out.println(string); 
    } 
} 

输出:

this 
that