Chris Vollink
Chris Vollink

Reputation: 11

Ignore Case of indexOf() with ArrayLists

static void seaArray()
    {
        String searchTerm = key.nextLine();

        for (int i = 0; i < name.size(); i++)
        {
            if (name.get(i).toLowerCase().indexOf(searchTerm.toLowerCase(), i) != -1)
            {
                printLn(name.get(i));
            }
            else
            {
                printLn("nope");
            }
        }


        promptCommand();
    }

I'm trying to allow the user to search for a name they have entered through characters. I've mostly ironed out the bugs, but I'd also like them to be able to do it without worrying about case. I searched this matter, and follwed the instructions offered, and it's still case sensitive.

Anyone mind helping me out?

More info: name is what I'm calling the arraylist. Thanks everbody for your input, ill try out eavh solution when I get the chance.

Upvotes: 1

Views: 5398

Answers (4)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41220

Use String#contains with lowercase.

for(String nm:name){
    if(nm.toLowerCase().contains(searchTerm.toLowerCase()))
        printLn(name.get(i));
    else
        printLn("nope");
}

Upvotes: 1

ryanprayogo
ryanprayogo

Reputation: 11817

Use equalsIgnoreCase() instead of equals()

Upvotes: 1

noahlz
noahlz

Reputation: 10311

Try using Collections.binarySearch(name, searchTerm, String.CASE_INSENSITIVE_ORDER)

(Unless you looking for name to be a sub-string of searchTerm?)

Upvotes: 1

Mike Kwan
Mike Kwan

Reputation: 24447

java.lang.String supplies a method called equalsIgnoreCase:

for(String str : name) {
    if(str.equalsIgnoreCase(searchTerm)) {
        ....
    } else {
        ....
    }
}

Upvotes: 1

Related Questions