首页  >  文章  >  Java  >  Java中如何使用栈来反转字符串?

Java中如何使用栈来反转字符串?

PHPz
PHPz转载
2023-05-07 11:13:19967浏览

使用堆栈

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基本数据类型有哪些

Java的基本数据类型分为:1、整数类型,用来表示整数的数据类型。2、浮点类型,用来表示小数的数据类型。3、字符类型,字符类型的关键字是“char”。4、布尔类型,是表示逻辑值的基本数据类型。

以上是Java中如何使用栈来反转字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:yisu.com。如有侵权,请联系admin@php.cn删除