Determine if string exists in file

前端 未结 2 1697
长情又很酷
长情又很酷 2021-01-28 22:35

I have a list of strings such as:

John

John Doe

Peter Pan

in a .txt file.

I want to make a loop that checks if a ce

2条回答
  •  甜味超标
    2021-01-28 23:00

    If you want to check for multiple names use a trie. If you have just one name, you can use KMP.

    I'll explain this for multiple names you want to check that exist, since for only one, the example provided on Wikipedia is more than sufficient and you can apply the same idea.

    Construct the said trie from your names you want to find, and for each line in file, traverse the trie character by character until you hit a final node.

    BONUS: trie is used by Aho-Corasick algorithm, which is an extension of KMP to multiple patters. Read about it. It's very worthwhile.

    UPDATE:

    For checking if a single name exists, hash the name you want to find, then read the text file line by line. For each line, hash it with the same function and compare it to the one you want to find. If they are equal, compare the strings character by character. You need to do this to avoid false positives (see hash collisions)

提交回复
热议问题