-1

Trying to reverse Strings individually using a stack in java. I have already wrote a code to output the entire String in reverse, but I need each individual word reversed but kept in the same order. What could I do to manipulate my code to make this work?

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 + "\"");
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
TDG44
  • 1

1 Answers1

0

If you need to break it up in to words, use StringTokenizer. This will break the string up into words. You can then reverse the characters in the word either through the code you wrote or as PeterLawrey suggested, create a StringBuilder and call the "reverse()" method.

doobop
  • 4,465
  • 2
  • 28
  • 39