Case insensitive matching in Java switch-case statement

跟風遠走 提交于 2019-11-26 21:47:12

问题


I was wondering if there is a way to perform case insensitive match in java switch case statement. the default implementation is case sensitive. Please see the example below.

public class SwitchCaseTest {

    /**
     * @param args
     */
     public static void main(String[] args) {

        switch ("UPPER") {
            case  "upper" :
                System.out.println("true");
                break;

            default:
                System.out.println("false");
                break;
        }
    }
}

So above statement returns false as output. And i am trying make it work for case-insensitive match like String.equalsIgnoreCase() would do. I tried to convert both the string literal to lower case and then compare. but was unable to do so.


回答1:


If you want to do that: just make sure the input data is in all lowercase, and use lowercase cases...

switch ("UPPER".toLowerCase()) {
case  "upper" :

....

Localization issues

Also, the ages old issue of localization strikes again, and plagues this thing too... For example, in the Turkish Locale, the uppercase counterpart of i is not I, but İ... And in return, the I is not transformed to i, but a "dotless i": ı. Don't underestimate this, it can be a deadly mistake...




回答2:


You try making everything uppercase or lowercase

String str = "something".toUpperCase();
switch(str){
case "UPPER":
}

or

String str = "something".toLowerCase();
swtich(str){
case "lower":
}

or even better use enum (note this is only possible from Java 7)

enum YourCases {UPPER1, UPPER2} // cases.
YourCases c = YourCases.UPPER1; // you will probably get this value from somewhere
switch(c){
case YourCases.UPPER1: ....
break;
case YourCases.UPPER2: ....
}



回答3:


try

switch ("UPPER".toUpperCase()) {
    case  "UPPER" :



回答4:


To avoid having to use the case expression to verify if it is lowercase or uppercase, I recommend that you use the following:

String value = String.valueOf(userChoice).toUpperCase();

This helps to make the conversion of lowercase to uppercase before doing the evaluation in the switch case.



来源:https://stackoverflow.com/questions/19180797/case-insensitive-matching-in-java-switch-case-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!