使用堆栈单独反转单词

时间:2013-09-22 21:14:17

标签: java stack

尝试使用java中的堆栈单独反转字符串。我已经编写了一个代码来反向输出整个String,但我需要将每个单词反转但保持相同的顺序。我该怎么做才能操纵我的代码才能使其工作?

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 + "\"");
    }
}

1 个答案:

答案 0 :(得分:0)

如果您需要将其分解为单词,请使用StringTokenizer。这会将字符串分解为单词。然后,您可以通过您编写的代码或PeterLawrey建议的方式反转单词中的字符,创建StringBuilder并调用“reverse()”方法。

相关问题