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.example.lang;

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

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

        // We use StringTokenizer 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 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 StringTokenizer to split a string?

The code below is an example of using StringTokenizer to split a string. In the current JDK this class is discouraged to be used, use the String.split() method instead or using the new java.util.regex package.

package org.kodejava.example.util;

import java.util.StringTokenizer;

public class StringTokenizerExample {
    public static void main(String[] args) {
        StringTokenizer st =
                new StringTokenizer("A StringTokenizer sample");

        // get how many tokens inside st object
        System.out.println("Tokens count: " + st.countTokens());

        // iterate st object to get more tokens from it
        while (st.hasMoreElements()) {
            String token = st.nextElement().toString();
            System.out.println("Token = " + token);
        }

        // split a date string using a forward slash as delimiter
        st = new StringTokenizer("2005/12/15", "/");
        while (st.hasMoreElements()) {
            String token = st.nextToken();
            System.out.println("Token = " + token);
        }
    }
}

Here is the result of this sample code:

Tokens count: 3
Token = A
Token = StringTokenizer
Token = sample
Token = 2005
Token = 12
Token = 15