-1
嘗試單獨使用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 + "\"");
}
}
或此:http://stackoverflow.com/questions/2713655/reverse-a-given-sentence-in-java – olydis
你正在推動個人角色,沒有文字。順便說一句StringBuilder.reverse()這樣做,如果這是你想要的。 –
逐字地做同樣的事情... – assylias