我是编程新手,正在参加初级编程类(class)。我试着四处寻找我的答案,我发现了可能有用的结果,但我不明白如何在使用堆栈时实现它们。我试图在不反转整个字符串的情况下反转字符串的单个单词。
例如:用户输入句子“Pies are great!”我需要输出为“seiP era !taerg”
到目前为止,我已经成功地编写了一个程序来反转整个字符串,因此使用上面示例的输出是:"!taerg era seiP"如您所见,我想反转单词本身而不用颠倒单词的顺序,但我必须使用堆栈来获取输入。
以下是我目前的情况:
public class ReversedString{
private static ArrayStack<String> stack;
public static void main(String[] args) {
stack = new ArrayStack<String>();
String string = "";
String stringReversed = "";
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the string that you want to reverse: ");
string = scanner.nextLine();
string.split(" ");
for(int i=0; i<string.length(); i++){
stack.push(string.substring(i, i+1));
}
while(!stack.isEmpty()){
stringReversed += stack.pop();
}
System.out.println("The reverse of the string is: " + stringReversed);
最佳答案
read character
while character is whitespace
// do nothing to skip multiple whitespaces.
read character
while character is not whitespace
push character onto stack
read character
// Just read a word, so now dump it back out.
while stack is not empty
ch = pop stack
print ch
显然,这需要在循环中才能执行多个单词。
读取字符
的示例实现
int index = 0;
String theString = "Pies are great!"
char readCharacter()
{
// TODO: needs error checking so you don't run off the end of the string.
char ch = theString.charAt(index);
index++;
return ch;
}
关于java - 如何在使用堆栈时反转字符串中的单个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14700893/