Search code examples
javaobjectif-statementarraylistignore-case

I want to compare an arrayList object with a String, ignoring case. How can I do this?


Following code written in Java

public static void main (String [] args) throws Exception
{
    ordListe ol = new ordListe();
    ol.lesBok("navn.text");
    ol.leggTilOrd("hello");
    ol.leggTilOrd("Hello");

Is my main method. This is about reading from file and adding to a arraylist(dictionary). ''Hello'' and "hello" is supposed to be the same word, and in the code under, it should increase the count of that word.

for (int i = 0; i < ordListe.size(); i++)
    {
        if (ordListe.toString().contains(s))
        {
            if (ordListe.get(i).toString().equalsIgnoreCase(s))
            {
                ord.oekAntall();
                System.out.println("'" + s + "' That word is found and there are " + ord.hentAntall() + " of that word now in dictionary.");
                break;
            }
        }

        else
        {
            Ord ny = new Ord(s);
            ordListe.add(ny);
            System.out.println("'" + s + "' This word is added. " + ny.hentAntall() + " of this word in dictionary.");
            break;
        }
    }

So this is a part of my code. From the main method I add words like ol.leggTilOrd("hello"); leggTilOrd is my method where the code right above is taken from. This is the part of the code that adds words to the dictionary/arrayList and checks if inputwords already exists. I have no problem with anything else than the specific if (ordListe.get(i).toString().equalsIgnoreCase(s)) part. If a word exist in the arrayList, I'm supposed to increase the count of that word. If not, I add the word in the arraylist (ordListe). The problem is that even if I add ol.leggTilOrd("hello") or ol.leggTilOrd("Hello"); with capital 'H', I can't get to recognize it as the same word even if I use the statements above. How do I do this, any other possibilites? This is my last possible effort, after many attempts earlier.

If there are anything questionable above, just tell me.


Solution

  • Change both strings to lower case before comparing and then comapare..it will help you and is easier!!! Use toLower function and then compare