如何比较循环中两个不同文件的两个字符串 [英] How do I compare two strings from two different files in a loop

查看:80
本文介绍了如何比较循环中两个不同文件的两个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我的程序打算用行号打印出文件2中找不到的单词。但是,我的程序循环有些混乱。



我尝试过:



Like my program supposed to print out the words that are not found in file 2 with the line number. However, my program's loop is kind of messed up.

What I have tried:

import java.util.Scanner;
import java.io.*;
public class SpellCheck{
    public static void main(String[] arg) throws FileNotFoundException{
        Scanner readPaper = new Scanner(new File("1.txt"));
  
        while(readPaper.hasNextLine()){
        String line = readPaper.next();
        Scanner linescan = new Scanner(line);
        String wordInPaper = linescan.next();
        
        
        Scanner readDict = new Scanner(new File("2.txt"));
        String wordIn = readDict.next();
        if(!wordInPaper.contains(wordIn))
          System.out.print(wordInPaper);
          } 
              }
}

推荐答案

将文件1的所有单词读入数组或某种类型的清单。将文件2中的所有单词读入单独的数组中。使用循环或迭代器测试第一个列表中的每个单词,看它是否在第二个单词中。如果找不到该单词,则将其写出来。
Read all the words of file 1 into an array or list of some type. Read all the words from file 2 into a separate array. Use a loop or iterator to test every word from the first list to see if it is in the second. If the word is not found then write it out.


不使用数组,字典或其他容器对性能不利。链接列表或某个向量怎么样?你的工作结果也应该是字典和性能比较的替代方案



如果真的不可能,那么读取一个字符串对象中的第二个文件并在一个步骤中搜索文件1的每个单词。我知道这是一个糟糕的解决方案,但它没有数组:-O
Not to use an array, dictionary or other container is bad for performance. What about a linked list or some vector? Result of your work should also be an alternative like dictionary and a performance comparison

If really not possible, than read the second file in a one string object and search every word of file 1 in a single step. I know that it is a bad solution, but it is without an array :-O


试试这个:

Try this:
import java.util.Scanner;
import java.io.*;

public class SpellCheck{
    public static void main(String[] arg) throws FileNotFoundException{
        String dictionary = "";
        Scanner readDict = new Scanner(new File("2.txt"));
        // Build the dictionary list from file 2
        while(readDict.hasNext()){
            String word = readDict.next();
            dictionary = dictionary + " " + word;
        }
        System.out.println("Dict: " + dictionary);
        
        Scanner readPaper = new Scanner(new File("1.txt"));
        while(readPaper.hasNext()){
            String wordInPaper = readPaper.next();
            System.out.println("wordInPaper: " + wordInPaper);
            if(!dictionary.contains(wordInPaper))
            	System.out.println("Not found: " + wordInPaper);
        }
    }
}


这篇关于如何比较循环中两个不同文件的两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆