Skip to content
Advertisement

Java – Check if user input partialy matches another string?

I have a problem where i want to see if the input user has enterd partially matches, or as long as majority matches with the answer, if it does then it should print out “Almost correct”. For example lets say the answer is Football, but user instead puts in Footbol. It should then print out Almost correct.

here is what i tried. But the problem is that it just checks if the whole word is containd in ENG otherwise if even one Char is missing it doesnt work.

     if (Answer.equalsIgnoreCase(ENG)){
        r = "Correct";
    }
    else if (Answer.toLowerCase().contains(ENG.toLowerCase().)){
        r = "Almost correct";
    }
    else {
        r = "Wrong";
    }
    System.out.println(r)

Advertisement

Answer

This code is certainly not perfect, but it basically compares the Strings and saves how many characters matched the corresponding character in the other String. This of course leads to it not really working that well with different sized Strings, as it will treat everything after the missing letter as false (unless it matches the character by chance). But maybe it helps regardless:

String match = "example";
String input = "exnaplr";
int smaller;
if (match.length() < input.length())
    smaller = match.length(); else smaller = input.length();
int correct = 0;
for (int i = 0; i < smaller; i++) {
    if (match.charAt(i) == input.charAt(i)) correct++;
}
int percentage = (int) ((double) correct / match.length() * 100);

System.out.println("Input was " + percentage + "% correct!");
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement