Search code examples
javainputuser-inputstdstringignore-case

user input ignore case


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.

Solution

  • If you don't need a List you could use a Set initialized with a case-insensitive comparator:

    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");
    

    Now when you call remove, the case of the argument no longer matters. So both of the following lines would work:

    colors.remove("RED");
    

    or

    colors.remove("Red");
    

    But this will only work if you don't need the ordering that the List interfaces gives you.