Reputation: 11
I have used the .equals method to search for a String in an ArrayList, but the user has to write the exact name of the String. Is there a way to show the String that matches the user input containing ? If you for example search for 'Djang' and the String you are trying to find is 'Django'.
Upvotes: 1
Views: 125
Reputation: 1804
You should check out the Levenshtein Distance. It measures how far away a string is from another string. There is even a Java implementation in Wikibooks.
Then, it's a matter of sorting and finding the minimum.
list.stream()
.sort(Comparator.comparing(
s -> LevenshteinDistance.computeLevenshteinDistance(s, input))
.findFirst();
From there, it's also possible to filter to add an upper bound on the acceptable distance to prevent all inputs from returning a result.
list.stream()
.sort(Comparator.comparing(
s -> LevenshteinDistance.computeLevenshteinDistance(s, input))
.filter(s -> LevenshteinDistance.computeLevenshteinDistance(s, input) < limit)
.findFirst();
Upvotes: 3
Reputation: 3364
try the String.contains() method
public boolean contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values.
Parameters: s - the sequence to search for
Returns: true if this string contains s, false otherwise
Throws: NullPointerException - if s is null
Since: 1.5
For example:
String myString = "Django"
public boolean stringCatcher(String userInput) {
return myString.contains(userInput);
}
then passing Djang
to stringCatcher()
would result in a true
value being returned.
Upvotes: 0