Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

string - Case insensitive matching in Java switch-case statement

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...