2011-06-08 5 views
0

挨拶全員;Javaで特定の単語が見つかると、長い文を短い文に分割する

私は[from、to、in、then]のようないくつかの単語を含むString型のLinkedListを持っています と私は長い文章を含むテキストファイルを持っています。 私がしたいことは、上記の単語の1つが見つかると、短い文でそれらの文を分割することです。

私がこれまで行ってきたことは、単語を含むリンクリストと、ファイル内の長い文章を含む別のリンクリストでした。 私は長い文章を分割する方法を知らないのですか?

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

答えて

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

私は単語のすべてのリストを反復したい場合は[from、to、in、then、しかし]これを試しましたが、Exeption 'String [] temp = null; (int j = 0; j Daisy

+0

私はこの例を編集しました。 –

0

どういう意味ですか?

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

返信いただきありがとうございますが、私はスペース上にないリストの各単語を分割することを意味します。 – Daisy

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 
関連する問題