Case insensitive matching in Java switch-case statement

前端 未结 4 1875
再見小時候
再見小時候 2020-12-01 23:44

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

相关标签:
4条回答
  • 2020-12-02 00:08

    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: ....
    }
    
    0 讨论(0)
  • 2020-12-02 00:19

    try

    switch ("UPPER".toUpperCase()) {
        case  "UPPER" :
    
    0 讨论(0)
  • 2020-12-02 00:27

    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.

    0 讨论(0)
  • 2020-12-02 00:30

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

    0 讨论(0)
提交回复
热议问题