簡體   English   中英

我想將arrayList對象與String進行比較,忽略大小寫。 我怎樣才能做到這一點?

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

以下用Java編寫的代碼

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

是我的主要方法。 這是關於從文件讀取並添加到arraylist(dictionary)。 “ Hello”和“ hello”應該是同一個詞,在下面的代碼中,應增加該詞的數量。

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;
        }
    }

所以這是我的代碼的一部分。 從主要方法中,我添加了ol.leggTilOrd("hello");類的ol.leggTilOrd("hello"); leggTilOrd是我的方法,上面的代碼來自此方法。 這是代碼的一部分,它將單詞添加到dictionary / arrayList並檢查輸入單詞是否已經存在。 除了特定的if (ordListe.get(i).toString().equalsIgnoreCase(s))部分外,我沒有任何問題。 如果arrayList中存在一個單詞,則應該增加該單詞的數量。 如果沒有,我將單詞添加到arraylist(ordListe)中。 問題是,即使我添加了ol.leggTilOrd("hello")ol.leggTilOrd("Hello") 如果使用大寫字母“ H”,即使使用上述語句,我也無法將其識別為同一詞。 其他任何可能性,我該怎么做? 經過較早的嘗試,這是我最后的嘗試。

如果上面有任何問題,請告訴我。

在比較之前將兩個字符串都更改為小寫,然后進行comapare ..它將為您提供幫助,並且更加簡單!!! 使用toLower函數,然后進行比較

問題是這一行:

if (ordListe.toString().contains(s))

因為1)您沒有比較兩個字符串的小寫或大寫版本,並且2)您可能沒有覆蓋toString,所以它按預期返回了列表中的項目。 假設您的ordliste擴展了arraylist,請將此函數放在ordListe類中:

public boolean containsIgnoreCase(String item) {
     for(int i = 0; i < size(); i++) {
           if (get(i).toString().equalsIgnoreCase(item)) {
               return true;
           }
     }

     return false;
}

現在,您可以調用containsIgnoreCase來確定列表中是否存在忽略大小寫的特定項目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM