2014-11-06 125 views
0

我想將大文本文件拆分爲單個單詞,因爲我需要對每個單詞的字母進行整理。將字符串數組拆分爲另一個數組?

ReadFile file = new ReadFile(file_name); 
String[] aryLines = file.OpenFile(); 

這節目我與文字文本文件閱讀,並給出的輸出:

[This is Line One. , This is Line Two. , This is Line three. , End.] 

如何分成這個{這是,線,一條}等? 我試圖

aryLines.split("\\s+"); 

,但它不工作作爲aryLines是一個數組...

+0

您必須爲每行使用例如一個for循環 – Philippe 2014-11-06 16:30:06

+0

試試這個:'aryLines。split(「」);'這應該強制行分裂成單個單詞。如果你想要包含標點符號,那麼你將不得不操作你的'split()'來併入它。 – Ckrempp 2014-11-06 16:36:00

回答

0
for (String string : arrLines) { 
      string.split(","); 
    } 

你已經和數組,你只需要爲每個做,分裂每個陣列中的內容,您得到。

我希望這對你有所幫助。

0

考慮:

String[] aryLines = { 
    "This is Line One.", "This is Line Two.", "This is Line three.", "End." 
}; 

爲了得到你正在尋找的結果,你需要分割數組的內容,而不是該數組本身:

ArrayList<List<String>> arrayList = new ArrayList<List<String>>(); 
for (String aString : aryLines) { 
    arrayList.add(Arrays.asList(aString.split("\\s+"))); 
} 

如果打印arrayList它,你將會得到:

[[This, is, Line, One.], [This, is, Line, Two.], [This, is, Line, three.], [End.]] 
0

根據文件的大小,您可以將文件讀入一個String然後調用分裂與正則表達式像

string.split("(\\)"); 

這將使你的話(和標點符號)的字符串數組。

或者,如果文件非常大,您可以像現在一樣一行一行地讀取它,然後通過遍歷它並將拆分詞添加到集合中來分割每一行。

ReadFile file = new ReadFile(file_name); 
String[] aryLines = file.OpenFile(); 
List<String> words = new ArrayList<String>(); 
for (String line : aryLines) { 
    for (String word : line.split("\\ ")) { 
     words.add(word); 
    } 
} 
0

試試這個代碼:
在這裏,我剛開了第一部分的輸出,即,「這是一號線。」分裂並存儲在數組 「aryLines1」 定義爲{此,是,線,一條}

public class TestingArray { 

    public static void main(String[] args) throws IOException{ 


     File file = new File("D:\\1-PROJECTS\\test.txt"); 
     FileReader fr = new FileReader(file); 
     BufferedReader br = new BufferedReader(fr); 
     String s; 

     List<String> list = new ArrayList(); 
     while((s=br.readLine())!=null){ 
      list.add(s); 
     } 

     String[] aryLines = list.toArray(new String[0]);  
     String[] aryLines1 = aryLines[0].split(" "); 

     for(int i=0;i<aryLines1.length;i++){ 
      System.out.println(aryLines1[i].toString()); 
     } 

    } 

} 

輸出出來是: -



一個。

這是存儲在數組「aryLines1」中的內容。

類似地,可以使用(」「)和存儲在其它陣列以及拆分「aryLines」