如何在使用堆栈时反转字符串中的单个单词?

时间:2013-02-05 05:40:45

标签: java string stack reverse

我是编程新手,我正在上初级编程课程。我已经尝试寻找我的答案,我发现可能有效的结果,但我不明白如何在使用堆栈时实现它们。我试图在没有反转整个字符串的情况下反转字符串的单个单词。

例如:用户输入句子“馅饼很棒!”我需要输出为“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);

4 个答案:

答案 0 :(得分:1)

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

显然,这需要循环来做多个单词。

read character

的示例实施
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;
}

答案 1 :(得分:0)

用像" "这样的空格(String#split)拆分句子你会得到分裂的字符串,它将是单词(“Pies”,“are”,“great!”)然后推送进入堆栈并单独弹出值。

String str ="Pies are great!";
String[] strs = str.split(" "); // "Pies", "are", "great!"
String newStr = "";
for(String str1:strs){
   //push str1
   // pop str1 and add it to newStr
}

答案 2 :(得分:0)

尝试

    Scanner sc = new Scanner("Pies are great!");
    while(sc.hasNext()) {
        System.out.print(new StringBuilder(sc.next()).reverse() + " ");
    }

输出

seiP era !taerg 

或使用java.util.Stack

    StringBuilder sb = new StringBuilder();
    Scanner sc = new Scanner("Pies are great!");
    while (sc.hasNext()) {
        Stack<Character> st = new Stack<>();
        for (char c : sc.next().toCharArray()) {
            st.push(c);
        }
        while (!st.isEmpty()) {
            sb.append(st.pop());
        }
        sb.append(' ');
    }
    System.out.print(sb);

输出

seiP era !taerg 

答案 3 :(得分:0)

使用您已编写的代码使用堆栈反转整个String,并将其转换为自己的方法。您的堆栈对于以相反顺序检索字母非常有用(后进先出)。类似的东西:

public String reverse(String str) {
  . . .
}

在main方法中,将String拆分为多个单词,并将每个单词迭代地传递给反向方法。不要使用堆栈的话。你的话是FIFO,堆栈提供LIFO。