search

Home  >  Q&A  >  body text

java题目 任意一个字符串 倒置输出,保持单词的完整性

java题目 任意一个字符串 倒置输出,保持单词的完整性


   StringBuffer sb = new StringBuffer("this is a apple");

   //不使用split方法  输入 apple a is this


   function reverse(StringBuffer sb){
      //方法中该如何写?
     
   }
怪我咯怪我咯2802 days ago639

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-18 10:49:47

    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;
        }

    reply
    0
  • Cancelreply