Skip to content
Related Articles
Open in App
Not now

Related Articles

Reverse words in a given String in Java

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 18 Jul, 2022
Improve Article
Save Article

Let’s see an approach to reverse words of a given String in Java without using any of the String library function Examples:

Input : "Welcome to geeksforgeeks"
Output : "geeksforgeeks to Welcome"

Input : "I love Java Programming"
Output :"Programming Java love I"

Prerequisite: Regular Expression in Java 


// Java Program to reverse a String
// without using inbuilt String function
import java.util.regex.Pattern;
public class Exp {
    // Method to reverse words of a String
    static String reverseWords(String str)
        // Specifying the pattern to be searched
        Pattern pattern = Pattern.compile("\\s");
        // splitting String str with a pattern
        // (i.e )splitting the string whenever their
        // is whitespace and store in temp array.
        String[] temp = pattern.split(str);
        String result = "";
        // Iterate over the temp array and store
        // the string in reverse order.
        for (int i = 0; i < temp.length; i++) {
            if (i == temp.length - 1)
                result = temp[i] + result;
                result = " " + temp[i] + result;
        return result;
    // Driver methods to test above method
    public static void main(String[] args)
        String s1 = "Welcome to geeksforgeeks";
        String s2 = "I love Java Programming";


geeksforgeeks to Welcome
Programming Java love I

Time Complexity: O(n), where n is the length of the string.

Auxiliary Space: O(n)

You can find the c++ solution for Reverse words in a String here This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!