java题目 任意一个字符串 倒置输出,保持单词的完整性
问题描述
java题目 任意一个字符串 倒置输出,保持单词的完整性StringBuffer sb = new StringBuffer('this is a apple'); //不使用split方法 输入 apple a is this function reverse(StringBuffer sb){ //方法中该如何写?}
问题解答
回答1:public static void main(String[] args) {StringBuffer sb = new StringBuffer('this is a apple');System.out.println(reverse(sb)); }public static StringBuffer reverse(StringBuffer sb) {StringBuffer ret = new StringBuffer();char[] charArray = sb.toString().toCharArray();StringBuffer temp = new StringBuffer();for(int i = charArray.length-1; i >= 0; i--) { if ((charArray[i] >= ’a’ && charArray[i] <= ’z’) || (charArray[i] >= ’A’ && charArray[i] <= ’Z’)) {temp.append(charArray[i]);if (i==0) { ret.append(temp);} } else {ret.append(temp);ret.append(' ');temp.delete(0, temp.length()); }}return ret; }