-1

I try to find a book by its title.

Let's say the book "Jungle" exists. I want to find it even if I search for

  • "JunGLE" : works,
  • "Jung" : works,
  • "JunG" : does not work.

I hope you understand. I use matches to add all the books that matches that title in the search. Does anyone know how to fix this?

public ArrayList<Book> search(String title){
    ArrayList<Book> matches = new ArrayList<>(); 
    for (Book b : Books){
        String s = b.getTitle();
        if(s.equalsIgnoreCase(title)||s.trim().contains(title))
            matches.add(b);
    }
    return matches;
}
azro
  • 53,056
  • 7
  • 34
  • 70
Zuzu
  • 19
  • 5
  • 1
    contains method is not case insensitive – Mladen Savić Oct 10 '18 at 15:14
  • 1
    why Jung and not JunG ? – azro Oct 10 '18 at 15:16
  • basically convert everything to uppercase (or lowercase) `s.toUpperCase().contains(title.toUpperCase())` – user85421 Oct 10 '18 at 15:18
  • @azro what do you mean ? "Jung" is the original name and what I mean is that if I search with parts of the name I can find the book, but if I search with parts of the name but upper case (as not in the original name) does not work. – Zuzu Oct 10 '18 at 15:19
  • @Zuzu you havew to better explain (edit your post), you mean that is has to be (same word zith case insensitive) OR (part ofword case sensitive) ? – azro Oct 10 '18 at 15:21
  • I'd go with a more robust solution based on RegEx – Diego Oct 10 '18 at 15:23
  • So your code should be working, explain what does not work – azro Oct 10 '18 at 15:24
  • @azro the question is pretty clear, OPs is saying what is currently working and what is not. – Federico klez Culloca Oct 10 '18 at 15:25
  • @FedericoklezCulloca ow this is a mis-sense, the enumeration is not the expectation, but what he actually has and every one should work but that-s not said at all ;) – azro Oct 10 '18 at 15:27

1 Answers1

2

contains is case-sensitive, so if you want a case-insensitive search then one commonly used method is to force both sides to the same case (upper or lower, it doesn't matter, as long as you use the same on both sides).

s.trim().toUpperCase().contains(title.toUpperCase())
Michael
  • 41,989
  • 11
  • 82
  • 128
  • The strange difference with Jung and JunG won't be working here, but this is the good solution though – azro Oct 10 '18 at 15:19
  • Sure it would work, `s` ("Jungle") would be converted to "JUNGLE" and `title` ("JunG") would be converted to JUNG, which is contained in `s` – Federico klez Culloca Oct 10 '18 at 15:23
  • That is not case insensitive searching, see https://stackoverflow.com/a/6996550 for a list of cases that could give problems – Ferrybig Oct 10 '18 at 16:33