2011-03-27 68 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方式。