0

I want to know if there is a way to compare a String to a text file to get the best possible answer. Example: We have a this in text file:

BANANA
BANTER
APPLE
BASKET
BASEBALL

and the current String is: B.N... (with the dots being the unknown characters). Is there a way to instantly get an array or hashmap with the possible letters (so A, T and E) out of the text file?

What I think I should do: I have managed to get every line of the text file in a arraylist. I should compare the current String to the possible answers in the arraylist and get every character in that word on the place of the dots and put it in a new arraylist.

Thanks in advance.

6
  • 1
    Post what you have tried so far Commented Jan 18, 2016 at 16:02
  • 2
    Sounds like a school project, what is your attempted code so far? Commented Jan 18, 2016 at 16:03
  • Is this like a spellchecking algorithm or is it an autocomplete algorithm? Reading up on the Aho-Corasick algorithm might be a step in the right direction. Commented Jan 18, 2016 at 16:07
  • Please see the help center Commented Jan 18, 2016 at 16:08
  • @JimW it is an autocomplete algorithm. And thanks I will check it out. Commented Jan 18, 2016 at 16:08

1 Answer 1

2

You could try to use regular expressions. Your current String "B.N..." must be translated into a Pattern, which you will match with the other words present in the text file. You can find a tutorial on regular expressions here.

Here's a little example:

public class RegexPlayground {
    public static void main(String[] args){
        Pattern pattern=Pattern.compile("B.N...");
        String word="BANANA";
        Matcher matcher = pattern.matcher(word);
        if(matcher.find()){
            System.out.println("Found matching word \""+word+"\"");
        }
        word="BASKET";
        matcher = pattern.matcher(word);
        if(matcher.find()){
            System.out.println("Found matching word \""+word+"\"");
        }else{
            System.out.println("No match on word \""+word+"\"");
        }
    }
}

Output:

Found matching word "BANANA"

No match on word "BASKET"

So the overall logic of the program should be like this:

String regex = getRedex(); // This is your B.N...
Pattern pattern = Pattern.compile(regex);
List<String> words=readFromFile(); // The list of words in the text file
for(String word: words){
    Matcher matcher = pattern.matcher(word);
    if(matcher.find()){
        // Match found
        // do what you need to do here
    }else{
        // Same here
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Worked perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.