2011-03-27 71 views
0

我正在閱讀用戶輸入。我想知道如何將equalsIgnoreCase應用於用戶輸入?用戶輸入忽略大小寫

ArrayList<String> aListColors = new ArrayList<String>(); 
    aListColors.add("Red"); 
    aListColors.add("Green"); 
    aListColors.add("Blue"); 

InputStreamReader istream = new InputStreamReader(System.in) ; 
BufferedReader bufRead = new BufferedReader(istream) ; 
String rem = bufRead.readLine(); // the user can enter 'red' instead of 'Red' 
aListColors.remove(rem); //equalsIgnoreCase or other procedure to match and remove. 
+0

equalsIgnoreCase是什麼? (另外,添加java標籤) – MByD 2011-03-27 09:42:38

回答

2

如果您不需要List你可以使用一個不區分大小寫的比較初始化一個Set

Set<String> colors = 
     new TreeSet<String>(new Comparator<String>() 
      { 
      public int compare(String value1, String value2) 
      { 
       // this throw an exception if value1 is null! 
       return value1.compareToIgnoreCase(value2); 
      } 
      }); 

colors.add("Red"); 
colors.add("Green"); 
colors.add("Blue"); 

現在當你調用刪除的說法不再是問題的情況下。所以,下面的兩個行會的工作:

colors.remove("RED"); 

colors.remove("Red"); 

但是這個,如果你不需要排序的List接口讓你纔會工作。

0

equalsIgnoreCase是String類的一個方法。

嘗試

someString.equalsIgnoreCase(bufRead.readLine()); 
0

如果你想忽略的情況下,當你找回你不能做到這一點。

取而代之,您需要將它放到列表中時將其全部大寫或全部小寫。

ArrayList<String> aListColors = new ArrayList<String>(); 
aListColors.add("Red".toUpperCase()); 
aListColors.add("Green".toUpperCase()); 
aListColors.add("Blue".toUpperCase()); 

然後,你可以做以後

aListColors.remove(rem.toUpperCase()); 
0

由於ArrayList.remove方法使用等於代替equalsIgnoreCase你必須通過自己的列表進行迭代。

Iterator<String> iter = aListColors.iterator(); 
while(iter.hasNext()){ 
    if(iter.next().equalsIgnoreCase(rem)) 
    { 
     iter.remove(); 
     break; 
    } 
} 
0

刪除集合中的方法是爲了移除equals()中的元素,意思是「Red」.equals(「red」)爲false,並且您無法在List中找到具有equalsIgnnoreCase的方法。這將只有絃樂感,使您可以編寫自己的類,並添加equals方法 - 什麼是等於你

class Person { 
    String name; 
    // getter, constructor 
    @Override 
    public boolean equals(Object obj) { 
     return (obj instanceof Person && ((Person)obj).getName().equalsIgnoreCase(name)); 
    } 
} 

public class MyHelloWorld { 
    public static void main(String[] args) { 
     List<Person> list = new ArrayList<Person>(); 
     list.add(new Person("Red")); 
     list.remove(new Person("red")); 
    } 
} 

或者沒有補償溶液等於:它通過列表迭代,找到你的「紅」,在寫方法equalsIgnoreCase方式。