简体   繁体   中英

Check if array contains string

Ok, I have this program that is supposed to store information about CDs that are available in txt file. The file stores the data in format 'artist[tab]album' on the same line. What I want to do, is to have user input search query, and the program return if the CD is in the database. So let's say we have Green Day[tab]American Idiot in .txt file on some line, and when users types in Green, the programs checks that file and returns true. But my problem is, my current algorithm requires the string to completely match, instead of partial. So the users needs to type Green Day[tab]American Idiot to get true on the query. How to fix it? Thanks. I am sure it is something I don't see as beginner.

This is the part of the program that manages the search in the array Artists, that contains all the data currently stored in the .txt file

 for (String e : artists){
        if(Arrays.asList(e).contains(search)){
         contains=true;   
        }

Why are you creating a list? You should use artist.contains(search) (yes, try to choose more relevant variable names). Also make sure you don't have null elements in the array or search is not null etc, but you can do something like:

for(String artist : artists) {
    if(artist.toLowerCase().contains(search.toLowerCase()) {
        contains = true;
        // break; <- you may want to break here
    }
}

You may want to toLowerCase() both of them for case-insensitive search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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