需要解析一个字符串,以便可以将每个单独的元素与另一个字符串中的元素进行比较

时间:2015-11-17 18:35:35

标签: java string parsing bufferedreader

我试图从一个文件中解析文本,这个文件是"这是一个测试。这是一个简单的测试。"我需要解析它,以便我可以将它与另一个字典的文件进行比较。这是拼写检查程序的一部分。我在实现r.readline和r.split方法时遇到了麻烦。

    String fileName2 = "test.txt";
    String line2 = null;
    String[] diction2 = new String [100];


    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader2 = 
            new FileReader(fileName2);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader2 = 
            new BufferedReader(fileReader2);
        int j=0;
        while((line = bufferedReader2.readLine()) != null) {
            //System.out.println(line);
            diction2[j]=line;
            System.out.println(diction2[j]);
             j++;
             //r.readline(line);
             //delimiter
             //r.split

             //need to parse line to get each individual word out and compare to dictionary
        }    

        // Always close files.
        bufferedReader2.close();            
    }
    catch(FileNotFoundException ex) {
        System.out.println(
            "Unable to open file '" + 
            fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println(
            "Error reading file '" 
            + fileName + "'");                   
        // Or we could just do this: 
        // ex.printStackTrace();
    }

1 个答案:

答案 0 :(得分:0)

修改

当你这样做时:

for(String word : words){
    //Do some action
}

这意味着它将把每个字符串放在"字"数组,一个接一个地存储在" word"并执行"做一些行动"为了它。

与写作相同:

for(int i = 0; i < words.length; i++){
    String word = words[i];
    //Do something
}

编辑结束。

在这里:

while((line = bufferedReader2.readLine()) != null) {

您已经在阅读该行了,您不能这样做:

String fileName2 = "test.txt";
String line = null;
String[] diction2 = new String [100];


try {
    // FileReader reads text files in the default encoding.
    FileReader fileReader2 = 
        new FileReader(fileName2);

    // Always wrap FileReader in BufferedReader.
    BufferedReader bufferedReader2 = 
        new BufferedReader(fileReader2);
    int j=0;
    while((line = bufferedReader2.readLine()) != null) {
        //System.out.println(line);
        diction2[j]=line;
        System.out.println(diction2[j]);
         j++;
         //There you get the list of all the words in the line
         String[] words = line.split(" ");
         for(String word : words){
             //Check your word here
         }
    }    

    // Always close files.
    bufferedReader2.close();            
}
catch(FileNotFoundException ex) {
    System.out.println(
        "Unable to open file '" + 
        fileName + "'");                
}
catch(IOException ex) {
    System.out.println(
        "Error reading file '" 
        + fileName + "'");                   
    // Or we could just do this: 
    // ex.printStackTrace();
}