/********************** * 字符串大小写转换并倒序输出 **********************/ //.... main()函数 String s = "eDCba"; String result = ""; //大小写互转、倒序 result = reverseChar(upAndDownCaseInter(s)); return result; }; private String reverseChar(String str) { return new StringBuffer(str).reverse().toString(); } private String upAndDownCaseInter(String str) { char[] c = str.toCharArray(); String ret = ""; for (int i = 0; i < str.length(); i++) { if ((int) c[i] >= 65 && (int) c[i] <= 90) { c[i] += 32; } else if ((int) c[i] >= 97 && (int) c[i] <= 122) { c[i] -= 32; } ret +=c[i]; } return ret; }
public class TestClassThree {
public static void main(String[] args) {
new TestClassThree().work();
}
private void work() {
String s = "eDCba";
System.out.println(upAndDownCaseInter(s));
s = "我有很多大小写!ghjYTUjhgJGU";
System.out.println(upAndDownCaseInter(s));
}
private String upAndDownCaseInter(String str) {
StringBuilder sbr=new StringBuilder();
for(char c:str.toCharArray()) {
if(Character.isLowerCase(c)) {
sbr.insert(0, Character.toUpperCase(c));
}else if(Character.isUpperCase(c)) {
sbr.insert(0, Character.toLowerCase(c));
}else {
sbr.insert(0, c);
}
}
return sbr.toString();
}
}
谢谢。
把2功能合并为1个功能,
StringBuilder()内存里快一点,
模式上,什么东西【new TestClassThree()】做某事【work()】明了易懂..
@Coca-code: 还有一点, 对没有大小写之分的字符也有处理
@风中的雪糕: 就是 sbr.insert(0, c);
可以参考 翻手算法