使用堆疊
package net.javaguides.corejava.string; import java.util.Stack; /** * * @author Ramesh Fadatare * */ public class ReverseStringUsingStack { // Function to reverse a string in Java using a stack and character array public static String reverse(String str) { // base case: if string is null or empty if (str == null || str.equals("")) return str; // create an empty stack of characters Stack < Character > stack = new Stack < Character > (); // push every character of the given string into the stack char[] ch = str.toCharArray(); for (int i = 0; i < str.length(); i++) stack.push(ch[i]); // start from index 0 int k = 0; // pop characters from the stack until it is empty while (!stack.isEmpty()) { // assign each popped character back to the character array ch[k++] = stack.pop(); } // convert the character array into string and return it return String.copyValueOf(ch); } public static void main(String[] args) { String str = "javaguides"; str = reverse(str); // string is immutable System.out.println("Reverse of the given string is : " + str); } }
輸出:
Reverse of the given string is : sediugavaj
Java的基本資料型別分為: 1.整數類型,用來表示整數的資料型態。 2、浮點類型,用來表示小數的資料型態。 3.字元類型,字元類型的關鍵字是「char」。 4.布林類型,是表示邏輯值的基本資料類型。
以上是Java中如何使用堆疊來反轉字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!