The examples in this article summarize the common methods of Java to achieve string output in reverse order, and share them with you for your reference. The specific methods are as follows:
1. The easiest thing to think of is to use toCharArray() of the String class and then 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 a string in reverse order using recursion.
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. Another option is not to define the string as a String class, but as a StringBuffer class, and use the reverse() method in the StringBuffer class to directly reverse the string.
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 that what this article describes will be helpful to everyone's learning of Java programming.