Home >Java >javaTutorial >How to use stack to reverse string in Java?
Use stack
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); } }
Output:
Reverse of the given string is : sediugavaj
The basic data types of Java are divided into: 1. Integer type, used to represent the data type of integers. 2. Floating point type, a data type used to represent decimals. 3. Character type. The keyword of character type is "char". 4. Boolean type is the basic data type that represents logical values.
The above is the detailed content of How to use stack to reverse string in Java?. For more information, please follow other related articles on the PHP Chinese website!