Java switch-case语句中不区分大小写的匹配 [英] Case insensitive matching in Java switch-case statement
问题描述
我想知道是否有办法在java switch case语句中执行不区分大小写的匹配。默认实现是区分大小写。请参阅下面的示例。
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;
}
}
}
所以上面的语句返回 false
作为输出。我正在尝试使其适用于不区分大小写的匹配,如 String.equalsIgnoreCase()
会这样做。我试图将字符串文字转换为小写,然后比较。但是无法这样做。
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.
推荐答案
如果你想这样做:只需确保输入数据全部为小写,并使用小写的情况......
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" :
....
本地化问题
此外,年龄较大的本地化问题再次出现,并且也困扰着这个问题......例如,在土耳其语语言环境中,的大写字母i
不是我
,但©
...作为回报,我
未转换为 i
,而是无点我:ı
。不要低估这一点,它可以 一个致命的错误 ......
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...
这篇关于Java switch-case语句中不区分大小写的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!