How do I reverse the order of words in a String?
Author: Deron Eriksson
Description: This Java example shows how reverse the order of words in a String.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

The reverseDelimited() method of the StringUtils class in the Commons LangS library offers a simple way to reverse the words in a String. This method takes two arguments. The first argument specifies the String to reverse. The second argument specifies the word delimiter, which is normally a space character. The ReverseWordsTest class demonstrates this:

package test;


import org.apache.commons.lang.StringUtils;

public class ReverseWordsTest {

	public static void main(String[] args) throws IOException {

		String str = "Let's reverse these words";
		System.out.println("Original:" + str);

		String reversed = StringUtils.reverseDelimited(str, ' ');
		System.out.println("Reversed words:" + reversed);



Here is the console output:


Original:Let's reverse these words
Reversed words:words these reverse Let's

Related Tutorials: