题目:
输入:一个字符串(由字母空格组成),一个长度
输出:将所有单词前后位置颠倒,大小写颠倒
例如:
输入:
This is a sample,16
输出:
SAMPLE A IS tHIS
public String trans(String s,int n) { //处理全部是空格的情况 if(s.trim().length() == 0) return s; s = s.substring(0,n); //校准s长度 if(s.length() ==0) return s;//处理长度为0 StringBuilder sb = new StringBuilder(); s = changeStr(s); //大小写反转 /* * 截取末单词置首 */ for (int i = s.length()-1; i >= 0; i--) { if(s.charAt(i)==' '){ String str = s.substring(i+1); sb.append(str+" "); s=s.substring(0,i); } } sb.append(s); return sb.toString(); } //大小写反转类 public String changeStr(String s) { StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { if (c <= 'z' && c >= 'a') { c = Character.toUpperCase(c); } else if (c <= 'Z' && c >= 'A') { c = Character.toLowerCase(c); } sb.append(c); } return sb.toString(); }