简体   繁体   中英

Case Sensitive matter in Java

I have a menu, with a "delete" option. That will delete from a list a town that the user introduced earlier. And I am asking you, is there any code that will ignore if the user will introduce upper case or lower case?

For example, if my list has 3 items: New York, Bucharest, Paris. If the user will try to delete one of the item from the list, if he writes "new york", the list of items will stay the same, because he didn't use upper cases and the program doesn't recognize the item.

Thank you very much to all of you!! I fixed it. Thank youu!!

for(i = 0 ; i < distanta.size() ; i++)

            {
                if(distanta.get(i).getNume().equalsIgnoreCase(name))
                    { 
                    distanta.remove(i);
                    }
            }

Here is the code I wrote. Thanks !!

Is your list a list of Strings?

If so, Strings have a YOURSTRING.equalsIgnoreCase("OTHERSTRING") fucntion that will return true if they match regardless of case, and false if they don't match.

String testString = "hello";
String testString2 = "HELLO";

//prints out true
System.out.println(testString.equalsIgnoreCase(testString2));

You can use equalsIgnoreCase() from the String object. You can call this statically, like so:

String foo = "new york"; 
if (foo == String.equalsIgnoreCase("NeW YoRK") { 
 // do something
 } 

You can use compareTo() or compareToIgnoreCase(). "ignoreCase" will ignore if the string has lower or upper letter, it will just compare them.

"hola que tal".compareToIgnoreCase("hola, que tal"); // Returns 0 or True
"hola que tal".compareToIgnoreCase("HOLA, que TAL"); // Returns 0 or True

"hola que tal".compareTo("hola, que tal"); // Returns 0 or True
"hola que tal".compareTo("HOLA, que TAL"); // Returns !=0 or False

Compare and CompareToIgnoreCase are just used with strings, however, equals or equalsIgnoreCase are faster.

You could use equalsIgnoreCase() to compare the input with menu item, this method compare strings ignoring case sensitiveness.

if (input.equalsIgnoreCase(menuItem)) {
   //do the logic
}

If your menu item="New York" and input="new york", the if condition will be true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM