Summary of common methods for Java to implement string output in reverse order

  • 2020-04-01 03:27:57
  • OfStack

This article summarizes the Java example to achieve the string output in reverse order of the common methods, to share with you for your reference. Specific methods are as follows:

1. The most obvious estimation is to use toCharArray() of the String class and output the array in reverse order.

The implementation code is as follows:


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. You can also use the subString() method provided by the String class to output the inverted String recursively.

The implementation code is as follows:


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. Instead of defining a String as a String class, define it as a StringBuffer class, and use the reverse() method in the StringBuffer class to directly reverse order strings.

The implementation code is as follows:


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

I hope this article will be helpful to your Java programming study.


Related articles: