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.
4

5 回答 5

2

如果您不需要 a ,则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");

现在,当您调用 remove 时,参数的大小写不再重要。所以以下两行都可以工作:

colors.remove("RED");

或者

colors.remove("Red");

但这仅在您不需要List接口为您提供的顺序时才有效。

于 2011-03-27T10:02:35.177 回答
0

equalsIgnoreCase 是 String 类的一个方法。

尝试

someString.equalsIgnoreCase(bufRead.readLine());
于 2011-03-27T09:44:35.163 回答
0

如果要忽略大小写,则在检索时不能这样做。

相反,当您将其放入列表时,您需要将其移动到全部大写或全部小写。

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

然后,您可以稍后再做

aListColors.remove(rem.toUpperCase());
于 2011-03-27T09:50:41.803 回答
0

由于 ArrayList.remove 方法使用 equals 而不是 equalsIgnoreCase 您必须自己遍历列表。

Iterator<String> iter = aListColors.iterator();
while(iter.hasNext()){
     if(iter.next().equalsIgnoreCase(rem))
     {
        iter.remove();
        break;
     }
}
于 2011-03-27T09:54:57.773 回答
0

集合中的方法 remove 被实现以删除 equals() 中的元素,因此 "Red".equals("red") 为假,您无法在 List 中找到具有 equalsIgnnoreCase 的方法。这仅对 String 有意义,因此您可以编写自己的类并添加 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"));
    }
}

或者没有覆盖equals的解决方案:编写遍历列表并以equalsIgnoreCase方式找到你的“红色”的方法。

于 2011-03-27T10:19:25.003 回答