w3resource
Java Programming Exercies

Java String Exercises: Reverse words in a given string

Java String: Exercise-45 with Solution

Write a Java program to reverse words in a given string.

Pictorial Presentation:

Java String Exercises: Reverse words in a given string

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 public static String WordsInReverse(String str1) {
  StringBuilder sb = new StringBuilder(str1);
  String StrRev = sb.reverse().toString();

  String[] words = StrRev.split(" ");
  StringBuilder reverse = new StringBuilder();
  for (String tmp: words) {
   sb = new StringBuilder(tmp);
   reverse.append(sb.reverse() + " ");
  }
  reverse.deleteCharAt(reverse.length() - 1);
  return reverse.toString();
 }

 public static void main(String[] args) {
  String str1 = "Reverse words in a given string";
  System.out.println("The given string is: " + str1);
  System.out.println("The new string after reversed the words: " + WordsInReverse(str1));
 }
}

Sample Output:

The given string is: Reverse words in a given string
The new string after reversed the words: string given a in words Reverse

Flowchart:

Flowchart: Java String Exercises - Reverse words in a given string

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to reverse a string using recursion.
Next: Write a Java program to reverse every word in a string using methods.

What is the difficulty level of this exercise?