简体   繁体   English

如何在ArrayList中搜索具有多个单词的String?

[英]How to search for String that has more than one word in ArrayList?

My search method works fine for one word strings, but not for two words or more. 我的搜索方法适用于一个单词字符串,但不适用于两个或更多单词。

I am supposed to check to see if the titleToFind matches a DVD title in the 我应该检查一下titleToFind是否与DVD标题匹配

ArrayList<DVD>DVDlist

My search method: 我的搜索方法:

public DVD search(String titleToFind) {
    for (DVD dvdEntry : DVDlist) {
        if (dvdEntry.GetTitle().equalsIgnoreCase(titleToFind)) {
            return dvdEntry;
        }
    }
    return null;
}

I am not sure how to approach this problem. 我不确定如何解决这个问题。

Your main problem is that you stop searching when you hit your first match (the return statement in the loop). 您的主要问题是,当您遇到第一个匹配项(循环中的return语句)时,您将停止搜索。 Below is an example of returning a list containing all the matches. 以下是返回包含所有匹配项的列表的示例。

If you are not allowed to use a list, you could return an int (number of matches) or csv of matches. 如果不允许使用列表,则可以返回int(匹配数)或csv匹配项。

public List<DVD> search(String titleToFind) {
    List<DVD> matches = new ArrayList<DVD>();    
    for (DVD dvdEntry : DVDlist) {
        if (dvdEntry.GetTitle().equalsIgnoreCase(titleToFind)) {
            matches.add(dvdEntry);
        }
    }

    return matches;
}

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

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