1

I am reading a text file into my program, and having the user search for a string. How can I make this so its case-insensitive? Here is a snippet of my code:

while (str1.hasNextLine())
{
    String line = str1.nextLine();
    line = line.replace(";", " ");
    if(line.contains(Val))
    {
        System.out.println(line);
    } 

}

Val is the string variable. It is the string that the user entered, and the string that, if found in the text file, will print out on the line. But I need it to be case-insensitive. For some reason when I use equals.IgnoreCase it doesn't work.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Paul
  • 49
  • 2
  • 11
  • 2
    [`equalsIgnoreCase`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)) has no dot – FDinoff Jun 27 '15 at 17:01
  • Other options where you can avoid creating intermediate strings: see [here](http://stackoverflow.com/questions/86780/is-the-contains-method-in-java-lang-string-case-sensitive) and [here](http://stackoverflow.com/questions/14018478/string-contains-ignore-case). – sstan Jun 28 '15 at 04:50

1 Answers1

6

In this scenario, make everything a unified case, and compare.

if (line.toLowerCase().contains(Val.toLowerCase())) {
    // logic
}

There are limitations on what contains can do. It only checks CharSequences and does so in a case-sensitive fashion. By introducing a common case, this eliminates the case sensitivity issue.

Tom
  • 16,842
  • 17
  • 45
  • 54
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 3
    As a note to OP: please don't call `Val.toLowerCase()` in the loop. Create an own variable which holds the "converted" String outside that loop and use that instead. – Tom Jun 27 '15 at 17:01
  • 1
    @Tom On the one hand, I agree. On the other hand, this may be premature optimisation, leading to the unnecessary creation of a new variable and not being faster at all. – Mr Lister Jun 27 '15 at 17:04
  • @MrLister Since `toLowerCase` returns a new String if `Val` isn't already in lowercase it is faster*. How much faster, on the other hand, depends on the size of the file. (*) HotSpot may replaces that call, but I wouldn't wait for that or rely on that. – Tom Jun 27 '15 at 17:25
  • 1
    ...In this simplistic scenario, why are you worried about speed? If this operation were done several million times over the normal course of its operations, I'd start worrying about its performance, but *here*? I don't see any reason to fret about it @Tom. – Makoto Jun 27 '15 at 17:26
  • @Makoto I'm more worried about the unnecessary multiple creation of equal Strings. The (relatively) better performace is a positive side effect. – Tom Jun 27 '15 at 17:32
  • 1
    Thank you guys for your help! – Paul Jun 27 '15 at 17:35