Home > Java > javaTutorial > How to use stack to reverse string in Java?

How to use stack to reverse string in Java?

PHPz
Release: 2023-05-07 11:13:19
forward
1025 people have browsed it

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);
}
}
Copy after login

Output:

Reverse of the given string is : sediugavaj
Copy after login

What are the basic data types of java

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template