简体   繁体   English

在arraylist advanced(Java)中搜索字符串

[英]Search string in arraylist advanced (Java)

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. 我使用.equals方法在ArrayList中搜索String,但是用户必须写出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'. 例如,如果你搜索'Djang',你想要找到的字符串是'Django'。

You should check out the Levenshtein Distance . 你应该看看Levenshtein距离 It measures how far away a string is from another string. 它测量字符串与另一个字符串的距离。 There is even a Java implementation in Wikibooks . Wikibooks中甚至还有一个Java实现

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();

try the String.contains() method 尝试String.contains()方法

public boolean contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values. public boolean contains(CharSequence s)当且仅当此字符串包含指定的char值序列时,返回true。

Parameters: s - the sequence to search for 参数:s - 要搜索的序列

Returns: true if this string contains s, false otherwise 返回:如果此字符串包含s,则返回true,否则返回false

Throws: NullPointerException - if s is null 抛出:NullPointerException - 如果s为null

Since: 1.5 自: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. 然后将Djang传递给stringCatcher()将导致返回一个true值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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