Paul
Paul

Reputation: 49

How to convert contains to equals.ignorecase?

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.

Upvotes: 1

Views: 330

Answers (1)

Makoto
Makoto

Reputation: 106460

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.

Upvotes: 6

Related Questions