Reverse words in string in Java

Learn to reverse each word in a sentence in Java with example. We will reverse words in string in place using StringBuilder and StringUtils classes.

Original String – how to do in java

Reverse words – woh ot od ni avaj

1. Reverse words in string – StringBuilder class

  • Tokenize each word using String.split() method.
  • Loop through string array and use StringBuilder.reverse() method to reverse each word.
  • Join all revered words to get back string.
String blogName = "how to do in java";
StringBuilder reverseString = new StringBuilder();

String[] words = blogName.split(" ");		//step 1

for (String word : words) 
{
    String reverseWord = new StringBuilder(word).reverse().toString();		//step 2
    reverseString.append(reverseWord + " ");								//step 3
}

System.out.println( reverseString.toString().trim() );		//verify reversed string

Program output.

woh ot od ni avaj

2. Reverse words in string – StringUtils class

StringUtils class is in Apache command lang library. Use it’s StringUtils.reverseDelimited() method to reverse each word and join the string.

String blogName = "how to do in java";

String reverseString = StringUtils.reverseDelimited( StringUtils.reverse(sentence), ' ' );

System.out.println( reverseString );

Program output.

woh ot od ni avaj

In this post, we learned to reverse each word in a sentence in Java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

5 thoughts on “Reverse words in string in Java”

    • // this is a little hard coded, you can’t use StringBuilder for this task
      String original = “Hi John”;
      String [] split = original.split(” “);
      String result = split[1] + ” ” + split[0];
      System.out.println(result);

      Reply
    • store it in character array .Overwrite accordance with reversal using INDEX OF CHARACTERS
      Here below is your program:-

      import java.util.Scanner;
      
      public class Reverse
      {
      	public static void main(String args[])
      	{
      		Scanner sc=new Scanner(System.in);
      
      		System.out.println("Enter the string:");
      
      		String s = sc.nextLine();
      
      		int l = s.length();
      
      		System.out.println("Length="+l);
      
      		char ch[] = s.toCharArray();
      
      		for(int i=l-1; i>=0; i--)
      		{
      			System.out.print(ch[i]);
      		}
      	}
      }
      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.