简体   繁体   中英

Reading a .txt file to see if a word is found in a different .txt file?

I am lost and in need of direction. I wrote my the code to scan through the book.txt, but how can I go about comparing the words from input.txt to the words within book.txt?

This would work i would think

Scanner scan = new Scanner("book.txt");

Set<String> list = new HashSet<String>();
String word = "";

while(scan.hasNextLine())
    list.add(scan.nextLine());
scan.close();
scan = new Scanner("input.txt");
while(scan.hasNextLine())
    if(!list.contains((word = scan.nextLine()))) //word from input.txt is not in book.txt
        System.out.println(word); //print the word to the console

scan.close();

If you cannot use a HashSet then create a hashFunction of your own.

Mostly used hashFunction is this:

public static int mod = 1000007;
private static Long hashFunction(String word) {
        long hash = 5831;
        for (int i = 0; i < word.length(); ++i) {
            hash *= 33;
            hash %= mod;
            hash += word.charAt(i);
            hash %= mod;
        }
        return hash;
    }

The basic idea of a hashFunction is to create a hash from it's word and then fill that array with a boolean true indicating it's presence.

When you create a whole hashTable with all the hash values set. Then just create a hash for the target word and check for it's presence in the hashTable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM