How do I reverse a string by word?

In the other examples on this website you might have seen how to reverse a string using StringBuffer, StringUtils from Apache Commons Lang library or using the CharacterIterator.

In this example you’ll see another way that you can use to reverse a string by word. Here we use the StringTokenizer and the Stack class.

package org.kodejava.util;

import java.util.Stack;
import java.util.StringTokenizer;

public class ReverseStringByWord {
    public static void main(String[] args) {
        // The string that we'll reverse
        String text = "Jackdaws love my big sphinx of quartz";

        // We use StringTokenize to get each word of the string. You might try
        // to use the String.split() method if you want.
        StringTokenizer st = new StringTokenizer(text, " ");

        // To reverse it we can use the Stack class, which implements the LIFO
        // (last-in-first-out).
        Stack<String> stack = new Stack<>();
        while (st.hasMoreTokens()) {
            stack.push(st.nextToken());
        }

        // Print each word in reverse order
        while (!stack.isEmpty()) {
            System.out.print(stack.pop() + " ");
        }
    }
}

How do I use the Stack class in Java?

Stack is an extension of the java.util.Vector class that provided a LIFO (last-in-first-out) data structure. This class provide the usual method such as push() and pop(). The peek method is used the get the top element of the stack without removing the item.

package org.kodejava.util;

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        // We stored some values in the stack object.
        for (int i = 0; i < 10; i++) {
            stack.push(i);
            System.out.print(i + " ");
        }
        System.out.println();

        // Searching for an item in the stack. The position returned
        // as the distance from the top of the stack. Here we search
        // for the 3 number in the stack which is in the 7th row of
        // the stack.
        int position = stack.search(3);
        System.out.println("Search result position: " + position);

        // The current top value of the stack
        System.out.println("Stack top: " + stack.peek());

        // Here we're popping out all the stack object items.
        while (!stack.empty()) {
            System.out.print(stack.pop() + " ");
        }
    }
}

The result of the code snippet:

0 1 2 3 4 5 6 7 8 9 
Search result position: 7
Stack top: 9
9 8 7 6 5 4 3 2 1 0