字符串倒叙输出

1. 利用String类的toCharArray(),倒序输出数组。

import javax.swing.JOptionPane;  
public class ReverseString {  
     public static void main (String args[]){  
         String originalString;  
         String resultString = "";     
            originalString = JOptionPane.showInputDialog("Please input a String: ");  
           char[] charArray = originalString.toCharArray();  
           for (int i=charArray.length-1; i>=0; i--){  
             resultString += charArray[i];  
         }  
           JOptionPane.showMessageDialog(null, resultString, "Reverse String", JOptionPane.INFORMATION_MESSAGE);  
     }  
 }  

 2. 利用String类提供的subString()方法,递归的办法输出倒序字符串

import javax.swing.JOptionPane;  
    public class ReverseString {  
     public static void reverseString (String str){  
        if (str.length() == 1){  
             System.out.print(str);  
         }  
        else{  
            String subString1 = str.substring(0, str.length()-1);  
             String subString2 = str.substring(str.length()-1);  
               System.out.print(subString2);  
               reverseString (subString1);           
         }  
    }  
       public static void main (String args[]){  
         String originalString;  
           originalString = JOptionPane.showInputDialog("Please input a String: ");  
           reverseString (originalString);       
     }  
 }  

 3. 不把字符串定义为String类,而是定义成一个StringBuffer类,用StringBuffer类中的reverse()方法直接倒序字符串。

 import javax.swing.JOptionPane;  
    public class ReverseString {  
     public static void reverseString (String str){  
         StringBuffer stringBuffer = new StringBuffer (str);  
            System.out.print(stringBuffer.reverse());  
     }  
        public static void main (String args[]){  
         String originalString;  
          originalString = JOptionPane.showInputDialog("Please input a String: ");  
           reverseString (originalString);         
     }  
 }  

 4.利用org.apache.commons.lang.StringUtils包的reverse()方法

 import javax.swing.JOptionPane; 
 import org.apache.commons.lang.StringUtils ;
    
 public class ReverseString {  
      public static void reverseString (String str){  
           System.out.print(StringUtils.reverse(str));  
     }  
      
     public static void main (String args[]){  
        String originalString;  
         originalString = JOptionPane.showInputDialog("Please input a String: ");  
         reverseString (originalString);         
     }  
 }  
 

 

你可能感兴趣的:(apache,swing)