字符大小写转换
char a = 'A';
a ^= (1 << 5);
//效果与下面两种一样 小写转大写写法一样
/*a = (char) (a ^ (1 << 5));
a = (char) (a + 32);*/
System.out.println(a);
原理:大小写字母相差32,又因为异或重要特性:不进位加法,所以大写字母和(1<<5)异或变成变成小写字母,小写字母和(1<<5)异或变成大写字母。
判断是否为大/小写字母/数字(正则表达式)
public class Test1 {
private static final Pattern p = Pattern.compile("[A-Z]+");
private static final Pattern numberPattern = Pattern.compile("[0-9]+");
public static void main(String[] args) {
String str = "A";
String number = "123";
Matcher m = p.matcher(str);
if (m.matches()) {
System.out.println("uppercase.");
} else {
System.out.println("lowercase.");
}
Matcher mNumber = numberPattern.matcher(number);
if (mNumber.matches()) {
System.out.println("number string is the \"0-9\"");
}
}
}
打印结果:
本文介绍了使用异或操作实现字符大小写转换的编程技巧,详细解释了大小写字母相差32的原理,并通过实例展示了如何利用异或特性进行转换。同时,文章提供了使用正则表达式判断字符串是否为大写字母或数字的方法。

被折叠的 条评论
为什么被折叠?



