2025-02-10

Java中字符串的反轉
首推方法:
public void convertStr(String str){ 
        //將String 對象轉換為可改變的StringBuffer類對象 
        //然後調用StringBuffer類的reverse()方法實現反轉 
        String strReverse=new StringBuffer(str).reverse().toString(); 
        System.out.println(strReverse); 
     
    }
其他方法:
public void convertStr(String str){ 
 
        for (int i=str.length()-1;i>=0;i–) 
        { 
            //每次倒序輸出一個字符 
            System.out.print(str.charAt(i)); 
        }    
    }
比較不可取的方法:麻煩
 
public  void convertStr(String str){ 
         
        String strNew=""; 
        String [] s=new String[str.length()]; 
        for (int x=0;x<str.length();x++ ) 
        { 
            s[x]=str.substring(x,x+1); 
        } 
        for (int x=str.length()-1;x>=0;x– ) 
        { 
            strNew+=s[x]; 
        } 
        System.out.println(strNew); 
    }

作者“loading”

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *