尝试使用 java 中的堆栈单独反转字符串。我已经编写了一个代码来反向输出整个字符串,但我需要将每个单词反转但保持相同的顺序。我可以做些什么来操纵我的代码来完成这项工作?
import java.util.Scanner;
import jss2.ArrayStack;
public class ReverseString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = "";
ArrayStack<String> stack = new ArrayStack<String>();
System.out.println("Enter a string to be reversed: ");
str = scanner.nextLine();
if (str == null || str.equals("")) {
System.out.println("Try Again!");
System.exit(0);
}
for (int i = 0; i < str.length(); i++) {
// pushes all the characters in the string
// one by one into the Stack
stack.push(str.substring(i, i + 1));
}
String strrev = "";
while (!stack.isEmpty()) {
// pops all the elements from the Stack
// one by one which reverses the stack
strrev += stack.pop();
}
System.out.println("Reverse of the string : \"" + strrev + "\"");
}
}