Open In App

Reverse words in a given String in Java

Last Updated : 29 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
// 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; 
            else
                result = " " + temp[i] + result; 
        } 
        return result; 
    } 

    // Driver methods to test above method 
    public static void main(String[] args) 
    { 
        String s1 = "Welcome to geeksforgeeks"; 
        System.out.println(reverseWords(s1)); 

        String s2 = "I love Java Programming"; 
        System.out.println(reverseWords(s2)); 
    } 
} 

Output:

geeksforgeeks to Welcome
Programming Java love I

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

Auxiliary Space: O(n)

Approach: Without using split() or trim()

By this approach, we can even remove extra trailing spaces and in between the words also.

Basically, this algorithm involves 3 steps.

  1. If you find white space, there can be two possibilities. 
  2. It might be end of a word or else extra trailing space in between the words.
  3. if it is not a white space, add the character to temporary word as shown in the below code.

Below is the implementation of above approach.

Java
import java.util.*;

class GFG {
    
    public static String reverseString(String s)
    {
        StringBuilder ans=new StringBuilder();
        
        String temp = "";
        for(int i=0;i<s.length();i++)
        {
            char ch = s.charAt(i);
            if(ch==' ')
            {
                //if we find white space add temp in the start
                if(!temp.equals(""))
                {
                    //adding in the front every time
                    ans.insert(0,temp+" "); 
                }
                
                temp = "";
            }
            else 
                temp += ch;
        }
      
        //just removing the extra space at the end of the ans
        return ans.toString().substring(0,ans.length()-1); 
        
    }
    
    public static void main(String[] args) {
        
        String s1="   Welcome to   Geeks For Geeks   ";
        System.out.println("Before reversing length of string : "+s1.length());
        String ans1=reverseString(s1);
        System.out.println("After reversing length of string : "+ans1.length());
        System.out.println("\""+ans1+"\"\n");
        
        String s2="   I Love Java   Programming      ";
        System.out.println("Before reversing length of string : "+s2.length());
        String ans2=reverseString(s2);
        System.out.println("After reversing length of string : "+ans2.length());
        System.out.println("\""+ans2+"\"");
        
    }
}
//This code is contributed by aeroabrar_31

Output
Before reversing length of string : 34
After reversing length of string : 26
"Geeks For Geeks to Welcome"

Before reversing length of string : 34
After reversing length of string : 23
"Programming Java Love I"

Time Complexity: O(N) N is length of string

Auxiliary Space: O(1) 

You can find the c++ solution for Reverse words in a String here


Next Article
Practice Tags :

Similar Reads