package test;
import org.junit.Test;
public class TestDemo {
public static final char ofLow = 1<<5;
public static final char ofUp = (char)(Character.MAX_VALUE-(1<<5));
public static final char upMinVal = 'A';
public static final char upMaxVal = 'Z';
public static final char lowMinVal = 'a';
public static final char lowMaxVal = 'z';
public char toLow(char ch) {
return (char)(ch|ofLow);
}
public char toUp(char ch) {
return (char)(ch&ofUp);
}
public String toUpStr(String str){
char[] charArray = str.toCharArray();
for (int i=0;i<charArray.length;i++){
char temp = charArray[i];
if (temp>=lowMinVal&&temp<=lowMaxVal){
charArray[i] = toUp(temp);
}
}
return new String(charArray,0,charArray.length);
}
public String toLowStr(String str){
char[] charArray = str.toCharArray();
for (int i=0;i<charArray.length;i++){
char temp = charArray[i];
if (temp>=upMinVal&&temp<=upMaxVal){
charArray[i] = toLow(temp);
}
}
return new String(charArray,0,charArray.length);
}
@Test
public void test (){
System.out.println(toUpStr("djdldj45..dldjldjddkjljkSHSHJSHJ"));
System.out.println(toLowStr("djdl23..djdldjldjddkjljkSHSHJSHJ"));
}
}
查看ASKii码表,发现A(01000001)与a(01100001)的二进制码的第五位有区别,第五位是1那么就是小写,是0就是大写,根据这个规律使用“按位与”,“按位或”就可以实现转换。我们知道“与”,“或”,“非”是针对二进制的操作要比“加”,“减”运算要快速,所以这段代码应该是最快的大小写转换。