用户输入忽略大小写
我正在阅读用户输入。我想知道如何将 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.
I am reading a user input. I was wondering how I would apply equalsIgnoreCase
to the user input?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您不需要
List
,您可以使用使用不区分大小写的比较器初始化的Set
:现在,当您调用remove 时,参数的大小写不再重要。因此,以下两行都可以工作:
or
但这仅在您不需要
List
接口为您提供的排序时才有效。If you don't need a
List
you could use aSet
initialized with a case-insensitive comparator:Now when you call remove, the case of the argument no longer matters. So both of the following lines would work:
or
But this will only work if you don't need the ordering that the
List
interfaces gives you.equalsIgnoreCase 是 String 类的一个方法。
尝试
equalsIgnoreCase is a method of the String class.
Try
如果你想忽略大小写,那么在检索时就不能这样做。
相反,当您将其放入列表中时,您需要将其移至全部大写或全部小写。
那么,你可以稍后再做
IF you want to ignore the case, you can't do it when you retrieve.
Instead, you need to move it to all caps or all lowercase when you put it in the list.
Then, you can do later
由于 ArrayList.remove 方法使用 equals 而不是 equalsIgnoreCase,因此您必须自己迭代列表。
Since the ArrayList.remove method uses equals instead of equalsIgnoreCase you have to iterate through the list yourself.
集合中的删除方法是为了删除 equals() 中的元素而实现的,这意味着 "Red".equals("red") 为 false,并且您无法在列表中找到具有 equalsIgnoreCase 的方法。这仅对 String 有意义,因此您可以编写自己的类并添加 equals 方法 - 什么等于您
或不覆盖 equals 的解决方案:编写迭代列表并以 equalsIgnoreCase 方式找到“红色”的方法。
Method remove in collections is implemeneted to remove elements in equals() meaning so "Red".equals("red") is false and you can't find method which has equalsIgnnoreCase in List. This would have sense only for String so you can write your own class and add equals method - what is equals to you
Or solution without override equals: write method which iterate through list and find your "red" in equalsIgnoreCase way.