使用堆栈
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中文网其他相关文章!