Open In App

Java Program To Reverse Words In A Given String

Last Updated : 05 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”

reverse-words

Examples

Input: s = “geeks quiz practice code” 
Output: s = “code practice quiz geeks”

Input: s = “getting good at coding needs a lot of practice” 
Output: s = “practice of lot a needs coding at good getting”

Algorithm:  

  • Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
  • Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.

Below is the implementation of the above approach: 

Java




// Java program to reverse
// a String
import java.util.*;
class GFG{
 
// Reverse the letters of
// the word
static void reverse(char str[],
                    int start,
                    int end)
{
  // Temporary variable to
  // store character
  char temp;
   
  while (start <= end)
  {
    // Swapping the first and
    // last character
    temp = str[start];
    str[start] = str[end];
    str[end] = temp;
    start++;
    end--;
  }
}
// Function to reverse words
static char[] reverseWords(char []s)
{
  // Reversing individual words as
  // explained in the first step
  int start = 0;
  for (int end = 0; end < s.length; end++)
  {
    // If we see a space, we reverse the
    // previous word (word between
    // the indexes start and end-1
    // i.e., s[start..end-1]
    if (s[end] == ' ')
    {
      reverse(s, start, end);
      start = end + 1;
    }
  }
 
  // Reverse the last word
  reverse(s, start, s.length - 1);
 
  // Reverse the entire String
  reverse(s, 0, s.length - 1);
  return s;
}
 
// Driver Code
public static void main(String[] args)
{
  String s =
  "i like this program very much ";
  char []p = reverseWords(s.toCharArray());
  System.out.print(p);
}
}
// This code is contributed by gauravrajput1


Output

much very program this like i

Time complexity: O(n)

Auxiliary Space: O(n)

Another Approach:

we can do the above task by splitting and saving the string in a reverse manner. 

Below is the implementation of the above approach:

Java




// Java program to reverse a
// string
public class ReverseWords
{
    public static void main(String[] args)
    {
        String s[] =
        "i like this program very much".split(" ");
        String ans = "";
        for (int i = s.length - 1; i >= 0; i--)
        {
            ans += s[i] + " ";
        }
        System.out.println("Reversed String:");
        System.out.println(ans.substring(0,
                           ans.length() - 1));
    }
}


Output:

Reversed String:
much very program this like i

Time Complexity: O(n) 

Auxiliary Space: O(n) for array s

Without using any extra space:
The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too.   

Below is the implementation of the above approach:

Java




// Java code to reverse a string
class GFG{
     
// Reverse the string
public static String[] RevString(String[] s,
                                 int l)
{   
    // Check if number of words is even
    if (l % 2 == 0)
    {       
        // Find the middle word
        int j = l / 2;
         
        // Starting from the middle
        // start swapping words at
        // jth position and l - 1 - j position
        while (j <= l - 1)
        {
            String temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
     
    // Check if number of words is odd
    else
    {       
        // Find the middle word
        int j = (l / 2) + 1;
         
        // Starting from the middle start
        // swapping the words at jth
        // position and l-1-j position
        while (j <= l - 1)
        {
            String temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
     
    // Return the reversed sentence
    return s;
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "getting good at coding " +
               "needs a lot of practice";
    String[] words = s.split("\s");   
    words = RevString(words, words.length);   
    s = String.join(" ", words);   
    System.out.println(s);
}
}
// This code is contributed by MuskanKalra1


Output:

practice of lot a needs coding at good getting

Time complexity: O(n)

Auxiliary Space: O(n)

Please refer complete article on Reverse words in a given string for more details!



Similar Reads

Java Program to Swap Corner Words and Reverse Middle Characters of a String
Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string. Input: "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input: "Hello Bye" Output: "Bye Hello" Methods: Using the concept of ASCII valuesUsing the split() method Method 1: Using the
5 min read
Program to reverse words in a given string in C++
Given a sentence in the form of string str, the task is to reverse each word of the given sentence in C++. Examples: Input: str = "the sky is blue" Output: blue is sky theInput: str = "I love programming" Output: programming love I Method 1: Using STL functions Reverse the given string str using STL function reverse().Iterate the reversed string an
6 min read
C++ Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Rec
7 min read
C Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Rec
3 min read
Python Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Rec
5 min read
C# Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Rec
4 min read
Javascript Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Rec
4 min read
Reverse words in a given String in Java
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 Code // Java Program to reverse a String
3 min read
Check if the given string of words can be formed from words present in the dictionary
Given a string array of M words and a dictionary of N words. The task is to check if the given string of words can be formed from words present in the dictionary. Examples: dict[] = { find, a, geeks, all, for, on, geeks, answers, inter } Input: str[] = { "find", "all", "answers", "on", "geeks", "for", "geeks" }; Output: YES all words of str[] are p
17 min read
Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read