本文執行個體匯總了Java實現字串倒序輸出的常用方法,分享給大家供大家參考。具體方法如下:
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); } }
希望本文所述對大家Java程式設計的學習有所協助。