2014-11-06 137 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”