Reversing a string word by word in java

Using a Stack and StringTokenizer seems to be a bit of an overkill here. A more simplified version could be written like this:

public static String reverse(final String input) {
  Objects.requireNonNull(input);
  final StringBuilder stringBuilder = new StringBuilder();
  for (final String part : input.split("\s+")) {
    if (!part.isEmpty()) {
      if (stringBuilder.length() > 0) {
        stringBuilder.insert(0, " ");
      }
      stringBuilder.insert(0, part);
    }
  }
  return stringBuilder.toString();
}

This uses the ability of split() to take a String apart based on a given Regex. So the string is split based on a sequence of one or more white-spaces, which matches your initial requirement. Note that split will return an empty array in case input is an empty string.

The for-each loop then works through the array and inserts the part at the beginning of the stringBuilder (except for the first time), which will effectively reverse the array. Most people would probably use a reverse for(i...) loop here, but because this is a code review I try to be extra correct, and this is the safer version: You cannot cause ArrayIndexOutOfBoundsExceptions with for-each.

Any leading/trailing white-space will cause empty parts to appear in the splitted list, so there is a check for it in the loop. I use isEmpty() here, as this is in general safer (as in: less chance to do typos) than length() > 0 and benefits from potential, internal optimizations of String in terms of execution speed. You could call trim() beforehand, but this would cause some unnecessary String operations and creations, so this version is more efficient.

Please also note the check for null at the beginning. The code would otherwise throw when trying to split on null, but it is considered good practice to check before-hand, as theoretically (not in this code but in other) you otherwise might leave the system in an undefined state.

I also make use of final, which allows some compiler optimizations and prevents you from some basic coding mistakes, which is considered good practice.

Testing

It is always a good idea to do some quick testing of the functionality including the basic edge-cases, so here it is:

To check whether or not I do correct white-space removal, I change stringBuilder.insert(0, " ") to stringBuilder.insert(0, "+") for the test, to make the white-space visible.

When testing with System.out.println(reverse("the sky is blue")); the result is:
blue+is+sky+the The initial requirement is met.

When testing with System.out.println(reverse(" t the sky ist blue ")); the result is:
blue+is+sky+the Leading, trailing and in-between white-spaces are correctly removed.

When testing with reverse("") the result is an empty String as expected.

When testing with reverse(null) a NullPointerException is thrown at the beginning of the function.

Skip to content

How to Reverse a String in Java Word by Word

Today we will learn How to Reverse a String in Java Word by Word and also how to reverse a string in java. So before start learning, we will make you know about reversing a string.

What is reversing a String?

Reversing a string means changing the positions of the characters in such a way that the last character comes in the first position, second last on the second position and so on.

For Example the reverse of learnprogramo is omargorpnrael

There are so many ways to reverse a string we will see it one by one.

1. Converting String into Bytes.
2. Using the Inbuilt reverse() Method of StringBuilder Class.
3. By Converting String to Character Array.
4. By Using toCharArray() Method.
5. Using ArrayList Object.
6. Reverse a String word by word.
7. Reverse a String in Java Using Recursion.
8. Reverse a String in Java Using For Loop.
9. Without Using Reverse Function.
10. Using Unicode Right to Left Override.

1. Converting String into Bytes

Converting String into Bytes is one of the java methods to reverse a string. In this program, we will use java inbuilt getBytes() method to convert the given string into the bytes[].

Steps to reverse a string by converting string into bytes:

1st Step: First create a temporary byte[] whose length should be equal to the length of the input string.

2nd Step: Now store the bytes in the reverse order into the byte[].

3rd Step: Finally create the new string the byte[] for storing the result.

So let us see how to write a java program to reverse a string using string into Bytes method.

//Learnprogramo
import java.io.*; 
import java.util.*; 
public class test 
{
public static void main(String[] args) 
{ 
String input = "learnprogramo";   
// getBytes() method to convert string  
// into bytes[]. 
byte [] strAsByteArray = input.getBytes();   
byte [] result =  
new byte [strAsByteArray.length];   
// Store result in reverse order into the 
// result byte[] 
for (int i = 0; i<strAsByteArray.length; i++) 
result[i] =  
strAsByteArray[strAsByteArray.length-i-1];   
System.out.println(new String(result)); 
} 
} 

Output:

reverse a string in java

2. Using the Inbuilt Reverse() Method of StringBuilder Class

In java the String Class do not have a reverse() method so we need to convert the given input string into StringBuilder. this method is done using the append method of the StringBuilder.

This method replaces all the character sequences in the reverse order. At last, the characters of the reversed string are printed by scanning from first to the last index.

//Learnprogramo
public class test 
{
public static void main(String[] args) 
{ 
String input = "Learnprogramo";  
StringBuilder input1 = new StringBuilder();   
// append a string into StringBuilder input1 
input1.append(input); 
// reverse StringBuilder input1 
input1 = input1.reverse();   
// print reversed String 
System.out.println(input1); 
} 
} 

Output:

reverse a string in java

3. By Converting String to Character Array

In this program, we will make use of character array for reversing a string. We will use the inbuilt method toCharAt().

Steps to Convert String to Character Array:

1st Step: First read the input String using scanner object scan.nextline() and store that string in the variable str.

2nd Step: Initialize char[]ch.

3rd Step: Here j is the length of the array, and the for loop starts as i>0. Loop prints the character from the index i-1 of array ch.

4th Step: Now print characters from the last index of char array.

//Learnprogramo
import java.util.*;
public class test 
{
public static void main(String[]args)
{
String str;
Scanner scan=new Scanner(System.in);
System.out.print("Enter a string : ");
str=scan.nextLine();	
char[] ch=str.toCharArray(); 
System.out.print("Reverse of a String is :"); 
int j=ch.length;
for(int i=j;i>0;i--)
{
System.out.print(ch[i-1]); 
}
}
} 

Output:

how to reverse a string in java

4. Using toCharArray() Method

In this program, we are going to use another inbuilt method called toCharArray(). In this method, we first scan the character array from both the sides i.e from the start and the last index simultaneously.

Step to Use toCharArray() Method:

1st Step: First set the first index to 0 and right index to -1 (length of the string).

2nd Step: Now swap the characters of the start index with the last index one by one.

3rd Step: Increase the left index by 1 using left++ and simultaneously decrease the right index by 1 using right++.

4th Step: Now, Continue till left becomes less than or equal to the right.

//Learnprogramo
public class test 
{
public static void main(String[] args) 
{ 
String input = "learnprogramo"; 
char[] temparray = input.toCharArray(); 
int left, right; 
right = temparray.length-1;   
for (left=0; left < right ; left++ ,right--) 
{ 
// Swap values of left and right 
char temp = temparray[left]; 
temparray[left] = temparray[right]; 
temparray[right]=temp; 
}   
for (char c : temparray) 
System.out.print(c); 
System.out.println(); 
} 
} 

Output:

how to reverse a string in java

5. Using ArrayList Object

In this program, we will use the ArrayList Object for reversing the string. First, we will convert the given string in the character array using java inbuilt method toCharArray(). After converting add all the characters in the ArrayList object. The Collection class reverse() method takes the list object.

For reversing the string we need to pass an ArrayList object which is in the form of a list of the characters.

Steps for Using ArrayList Object:

1st Step: First, copy all the content to the ArrayList Object.

2nd Step: Now create an object using ListIterator() method on ArrayList Object.

3rd Step: ListIterator is used to print the reversed list on the screen.

//Learnprogramo
import java.util.*;
public class test 
{
public static void main(String[] args) 
{ 
String input = "learnprogramo"; 
char[] hello = input.toCharArray(); 
List<Character> programo = new ArrayList<>();   
for (char c: hello) 
programo.add(c);   
Collections.reverse(programo); 
ListIterator li = programo.listIterator(); 
while (li.hasNext()) 
System.out.print(li.next()); 
} 
} 

Output:

using recursion

6. How to Reverse a String Word by Word

In this program, we will accept a string from the user and then print the reversed string on the screen.

Steps to Reverse a String Word by Word:

1st Step: Accept the input string from the user using a scanner object and store the input string in variable str.

2nd Step: Convert the string into char array using the method toCharArray() and then initialize to char[]ch.

3rd step: add ch[0] to the string word if the given block add the characters to the string word until we get the space.

4th Step: If space is found then else block is executed to reverse the word.

5th Step: the 2nd for loop is used to reverse the last word read by the else block.

//Learnprogramo
import java.util.*;
public class test 
{
public static void main(String[ ] arg) 
{
String str;
String word="";
Scanner scan=new Scanner(System.in);
System.out.print("Enter a string : ");
str=scan.nextLine();	 
char[] ch=str.toCharArray(); 
for(int i=0;i<(ch.length);i++)
{
if(ch[i]!=' ')
{
word=word+ch[i];				
}
else
{
for(int c=word.length();c>0;c--)
{
System.out.print(word.charAt(c-1)); 	   
}
System.out.print(" "); 	
word="";
} 	   
}
System.out.println("Reverse String is=");
for(int c=word.length();c>0;c--)
{    
System.out.print(word.charAt(c-1)); 	   
}
}
}

Output:

using for loop

7. Reverse a String in Java Using Recursion

Recursion is nothing but the function calls itself directly or indirectly. In this program, we will write a recursive method to reverse the string.

Steps to Reverse a String in Java Using Recursion:

1st Step: Create an object Using a Class StringRecursion r.

2nd Step: Now read the String using Scanner class and store it in variable s.

3rd Step: We have called the reverse method r.rev(s) and the reverse of the string is done.

4th Step: Now the Reverse String is Printed.

//Learnprogramo
import java.util.*;
public class test 
{
String rev(String str) {
if(str.length() == 0)
return " ";
return str.charAt(str.length()-1) + rev(str.substring(0,str.length()-1)); }
public static void main(String[ ] args) 
{
test r=new test();
Scanner sc=new Scanner(System.in);
System.out.print("Enter the string : ");
String s=sc.nextLine();
System.out.println("Reversed String: "+r.rev(s)); }
}

Output:

using while loop

8. Reverse a String in Java Using For Loop

In this program, we will use for loop to reverse a string in java. The for loop in program iterates from j=length of the string to j>0. Now it prints the character of the string from the index (i-1) and the reverse string is printed on the screen.

import java.util.*;
public class test 
{
public static void main(String[ ] arg)
{
String str;
char ch;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string : ");
str=sc.nextLine();	
System.out.println("Reverse of a String '"+str+"' is  :"); 
for(int j=str.length();j>0;--j)
{
System.out.print(str.charAt(j-1)); 
}
}
}

Output:

using functions

9. How to Reverse a String in Java Without Using Reverse Function

Now we will write a program to reverse a String in java without using a reverse function using while loop.

This while loop executes until the condition i>0 becomes false.

import java.util.*;
public class test 
{
public static void main(String[ ] arg)
{
String str;
Scanner scan=new Scanner(System.in);
System.out.print("Enter a string : ");
str=scan.nextLine();	
System.out.println("Reverse of a String '"+str+"' is  :"); 
int i=str.length();
while(i>0)
{
System.out.print(str.charAt(i-1)); 
i--;
}
}
}

Output:

reverse a string in java

10. Using Unicode Right to Left Override

In this program, we will use Unicode Right to Left Override Method to Reverse a String in java. Let us see how the program is written with output.

//Learnprogramo
import java.util.*;
public class test 
{
// Function to reverse a string in Java by Unicode
// Right-to-left Override (RLO) character
public static String reverse(String str)
{
return "u202E" + str;
}
public static void main (String[] args)
{
String str = "Learnprogramo";
// string is immutable
str = reverse(str);
System.out.println("Reverse of the given string is : " + str);
}
}

Output:

using different method in java

Conclusion:

we have discussed all the java methods to reverse a string. Hope you understand all the methods and if you have any doubt then please feel free to mention in the below comment box.

Also Read:

  • Program to print number pattern in java.
  • Java Program to Print Star Pattern.

learnprogramo@gmail.com2022-04-07T06:08:30+00:00

Ezoicreport this ad Related Posts

  • Given a string in java, reverse the string word by word.
  • Let us look into couple of examples to understand problem statement.
    • Example 1:
      • String inputString = “Girl Proposes Boy”
      • reverse(inputString) should be “Boy Proposes Girl”
    • Example 2:
      • String inputString = “Hell To Heaven”
      • reverse(inputString) should be “Heaven To Hell”

1. Algorithm: Reverse string word by word (java/ stack /stringbuilder)

  1. Reverse String using StringBuilder
    • Split the input string using space delimiter.
    • Start appending the string from end .
    • We will get string reversed word wise.
  2. Reverse String using Stack.
    • Split the input string using space delimiter.
    • Iterate through the string array (result of previous step) & push each string to stack.
    • Pop each string element from stack and concatenate the string.
    • We we get the desired output.

reverse string word stack java example

Fig 1: Reverse String word by word

2. Program: Reverse string word by word (java/stack/stringbuilder /example)

package org.learn;

import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Pattern;

public class ReverseWordsInString {

	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			System.out.printf("1. Enter string to reverse : ");
			String inputString = scanner.nextLine();
			
			if (inputString == null || inputString.length() == 0) {
				System.out.println("Enter the valid string");
				return;
			}
			
			String reverse = reverseStringWordWise(inputString);
			System.out.printf("2. Reverse string using StringBuilder is : %s", reverse);
			
			reverse = reverseStringWordWise_Stack(inputString);
			System.out.printf("n3. Reverse string using stack is : %s", reverse);
		}
	}

	private static String reverseStringWordWise(String inputString) {
		String[] arrString = inputString.trim().split(Pattern.quote(" "));
		StringBuilder builder = new StringBuilder();
		int length = arrString.length;

		while (--length >= 0) {
			builder.append(arrString[length]).append(" ");
		}

		return builder.toString();
	}
	
	private static String reverseStringWordWise_Stack(String inputString) {
		String[] arrString = inputString.trim().split(Pattern.quote(" "));
		Stack<String> stack = new Stack<>();
		for(String input : arrString) {
			stack.push(input);
		}
		
		StringBuilder builder = new StringBuilder();
		while( !stack.isEmpty()) {
			builder.append(stack.pop()).append(" ");
		}
		return builder.toString();
	}
}

3. Output: Reverse string word by word (java/stack/stringbuilder /example)

1. Enter string to reverse : Girl Proposes Boy
2. Reverse string using StringBuilder is : Boy Proposes Girl 
3. Reverse string using stack is : Boy Proposes Girl 

1. Enter string to reverse : Hell To Heaven
2. Reverse string using StringBuilder is : Heaven To Hell 
3. Reverse string using stack is : Heaven To Hell 

How to Reverse a String in Java is one of the popular interview questions, but the interviewer might add some twist to it by asking you to write the code without using the reverse() method, recursion, etc. In this article, we will learn the possible ways of reversing a string in Java. We will look into techniques of reversing a single word and group of words in a sentence [Word by Word]

Method 1: Using reverse() function — Using StringBuilder (or) StringBuffer

This is the easiest way of reversing a String, we can use reverse() method of either StringBuilder (or) StringBuffer.

Note: StringBuilder can give a better performance as it is not Synchronized. StringBuffer is Synchronized

import java.util.Scanner;

public class StringReverse
{
    public static void main(String[] args)
    {
        String reverseString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        //Pass input to constructor of StringBuilder
        StringBuilder inputStr = new StringBuilder(input);
        
        //Use reverse() method to reverse the String
        reverseString = inputStr.reverse().toString();
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}
    • Get the input string from the user and pass it to the constructor of the StringBuilder.
    • Use the reverse() method of the StringBuilder class to get the reversed String.

Output:

Java Reverse String

Method 2: Reverse String Using charAt()

import java.util.Scanner;

public class StringReverse
{
    public static void main(String[] args)
    {
        String reverseString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        //Convert input to inputArray using toCharArray()
        char[] inputArray = input.toCharArray();
        
        for(int i=inputArray.length-1;i>=0;i--)
        {
            reverseString = reverseString+inputArray[i];
        }
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}
  • Get the input string from the user and convert the input string into a character array inputArray using toCharArray() method
  • Iterate the inputArray from end to start, each time append it to the reverseString.

Output:

Enter string to reversed
JavaInterviewPoint
Original String : JavaInterviewPoint
Reversed String : tnioPweivretnIavaJ 

Method 3: using Recursion

package com.javainterviewpoint;

import java.util.Scanner;

public class StringReverse
{
    public static void main(String[] args)
    {
        String reversedString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        reversedString = reverseString(input);
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reversedString);
    }
    public static String reverseString(String input)
    {
        if(input.isEmpty())
            return input;
        
        //Call reverseString() function recursively
        return reverseString(input.substring(1)) + input.charAt(0);
    }
}
  • Get the input string from the user and pass the input string to the reverseString() method.
  • In the reverseString() method, we will be recursively subString() the first character of the input String and append it to the end using charAt() method.

Method 4: Using Stack

import java.util.Scanner;
import java.util.Stack;

public class StringReverse
{
    public static void main(String[] args)
    {
        StringBuilder reverseString = new StringBuilder();

        System.out.println("Enter string to reversed");

        // Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        // Create a stack of characters
        Stack<Character> stack = new Stack<Character>();

        // Push each character into the stack
        for (int i = 0; i < input.length(); i++)
        {
            stack.push(input.charAt(i));
        }

        // pop each characters from the stack until it is empty
        while (!stack.empty())
        {
            reverseString.append(stack.pop());
        }

        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}
  • Get the input string from the user.
  • Create a Stack of Character and push each character of the input string into the stack.
  • Pop each character from the stack until it is empty and append it to the reverseString.

Method 5: Using Collections reverse() method

  • Get the input string from the user
  • Create a List of Character (characterList) and push each character of the input string into the characterList.
  • Use Collections.reverse() method to reverse the elements of the characterList
  • Iterate the characterList from end to start, each time append it to the reverseString
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class StringReverse
{
    public static void main(String[] args)
    {
        StringBuilder reverseString = new StringBuilder();

        System.out.println("Enter string to reversed");

        // Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        //Create a list of characters
        List<Character> characterList =  new ArrayList<Character>();
        
        //Push each characters into the characterList
        for(Character c : input.toCharArray())
        {
           characterList.add(c);
        }
        
        //Reverse the List using Collections.reverse()
        Collections.reverse(characterList);
        
        //Convert ArrayList to String
        for(Character c : characterList)
        {
            reverseString.append(c);
        }

        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}

Java Reverse String Word by Word

All the above methods will work good for a single word, lets now learn how to reverse a string in Java word by word,
We will reverse each word in a sentence.

Method 1: Using StringBuffer

  • Get the input string from the user
  • Using split() method split the sentence into words and save them to a String array (words)
  • Iterate through the String array and use reverse() method of the StringBuffer class to reverse the String and keep appending the reversedString.
package com.javainterviewpoint;

import java.util.Scanner;

public class StringReverse
{
	public static void main(String[] args)
    {
        String reverseString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        // Split sentence into seperate words
        String[] words = input.split(" "); 
        
        // Iterate the String array
        for(String word : words)
        {
        	// Append each reversed Words
        	reverseString = reverseString + new StringBuilder(word).reverse().toString()+" ";
        }
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}

Output:

Enter string to reversed
Hello World
Original String : Hello World
Reversed String : olleH dlroW

Method 2: Using charAt()

  • Get the input string from the user
  • Using split() method split the sentence into words and save them to a String array (words)
  • Iterate through the String array and convert each word into a character array using toCharArray() method
  • Iterate through the character array in the decreasing order and each time append the character to the reverseString
package com.javainterviewpoint;

import java.util.Scanner;

public class StringReverse
{
	public static void main(String[] args)
    {
        String reverseString = "";
        
        System.out.println("Enter string to reversed");
        
        //Read the input from the user
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        // Split sentence into seperate words
        String[] words = input.split(" "); 
        
        // Iterate the String array
        for(String word : words)
        {
            //Convert input to inputArray using toCharArray()
            char[] inputArray = word.toCharArray();
            
            for(int i=inputArray.length-1; i>=0; i--)
            {
                reverseString = reverseString+inputArray[i];
            }
            reverseString = reverseString + " ";
            
        }
        
        System.out.println("Original String : "+input);
        System.out.println("Reversed String : "+reverseString);
    }
}

In this section, we reverse a string in Java word by word.

Example 1: Reverse a string word by word using recursion

Output:

How to Reverse a String in Java Word by Word

Example 2: Reverse a string word by word by using for loop

Output:

How to Reverse a String in Java Word by Word



Youtube
For Videos Join Our Youtube Channel: Join Now


Feedback

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook
twitter
pinterest





Given an input string, reverse the string word by word.

For example, given s = «the sky is blue», return «blue is sky the».

Java Solution

This problem is pretty straightforward. We first split the string to words array, and then iterate through the array and add each element to a new string. Note: StringBuilder should be used to avoid creating too many Strings. If the string is very long, using String is not scalable since String is immutable and too many objects will be created and garbage collected.

class Solution {
	public String reverseWords(String s) {
		if (s == null || s.length() == 0) {
			return "";
		}
 
		// split to words by space
		String[] arr = s.split(" ");
		StringBuilder sb = new StringBuilder();
		for (int i = arr.length - 1; i >= 0; --i) {
			if (!arr[i].equals("")) {
				sb.append(arr[i]).append(" ");
			}
		}
		return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
	}
}

Category >> Algorithms

If you want someone to read your code,
please put the code inside <pre><code>
and
</code></pre>
tags. For example:

<pre><code> 
String foo = "bar";
</code></pre>

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like 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

    import java.util.regex.Pattern;

    public class Exp {

        static String reverseWords(String str)

        {

            Pattern pattern = Pattern.compile("\s");

            String[] temp = pattern.split(str);

            String result = "";

            for (int i = 0; i < temp.length; i++) {

                if (i == temp.length - 1)

                    result = temp[i] + result;

                else

                    result = " " + temp[i] + result;

            }

            return result;

        }

        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(!temp.equals(""))

                    {

                        ans.insert(0,temp+" ");

                    }

                    temp = "";

                }

                else

                    temp += ch;

            }

            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+""");

        }

    }

    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 This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.

    Like Article

    Save Article

    In this article, we will discuss how to reverse a string by word using StringTokenizer class

    Note:

    • StringTokenizer is deprecated, however it is carried forward for backward compatibility
    • Instead of StringTokenizer, developer should prefer using length() method of String class after splitting

    Let us move forward to discuss on reversing a String by word using various approaches

    1. Using StringTokenizer class and iterating while-loop

    ReversingStringByWordUsingStringTokenizer.java

    package in.bench.resources.java.stringtokenizer.example;
    
    import java.util.StringTokenizer;
    
    public class ReversingStringByWordUsingStringTokenizer {
    
    	public static void main(String[] args) {
    
    		// sample string
    		String originalStr = "Water Earth Wind Sky Fire";
    		String reversedStr = "";
    
    		// create StringTokenizer object
    		StringTokenizer st= new StringTokenizer(originalStr, " ");
    
    		// reverse words
    		// by iterating through StringTokenizer tokens
    		while(st.hasMoreTokens()) {
    			reversedStr = st.nextToken() + " " + reversedStr;
    		}
    
    		// print to console
    		System.out.println("Reverse String "
    				+ "using StringToknizer & while-loop:n");
    		System.out.println("Original String : "
    				+ originalStr);
    		System.out.println("Reversed String : "
    				+ reversedStr.trim());
    	}
    }
    

    Output:

    Reverse String using StringToknizer & while-loop:
    
    Original String : Water Earth Wind Sky Fire
    Reversed String : Fire Sky Wind Earth Water
    

    2. Using StringTokenizer class and Stack class

    ReversingStringByWordUsingStack.java

    package in.bench.resources.java.stringtokenizer.example;
    
    import java.util.Stack;
    import java.util.StringTokenizer;
    
    public class ReversingStringByWordUsingStack {
    
    	public static void main(String[] args) {
    
    		// sample string
    		String originalStr= "Apple Banana Mango Orange Blueberry";
    		String reversedStr = "";
    
    		// declare Stack object to store &amp; retrieve tokens
    		Stack<String> stack = new Stack<String>();
    
    		// create StringTokenizer object
    		StringTokenizer st= new StringTokenizer(originalStr, " ");
    
    		// iterate and store tokens inside Stack
    		while(st.hasMoreTokens()) {
    			stack.push(st.nextToken());
    		}
    
    		// retrieve tokens from Stack by iterating
    		while(!stack.empty()) {
    			reversedStr = reversedStr + " " + stack.pop();
    		}
    
    		// print to console
    		System.out.println("Reverse String"
    				+ " using StringToknizer and Stack:n");
    		System.out.println("Original String : "
    				+ originalStr);
    		System.out.println("Reversed String : "
    				+ reversedStr.trim());
    	}
    }
    

    Output:

    Reverse String using StringToknizer and Stack:
    
    Original String : Apple Banana Mango Orange Blueberry
    Reversed String : Blueberry Orange Mango Banana Apple
    

    3. Using StringTokenizer class and iterating for-loop in reverse order

    ReversingStringByWord.java

    package in.bench.resources.java.stringtokenizer.example;
    
    import java.util.StringTokenizer;
    
    public class ReversingStringByWord {
    
    	public static void main(String[] args) {
    
    		// sample string
    		String originalStr = "USA RSA KSA IND UK GER RUS";
    		String reversedStr = "";
    
    		// create StringTokenizer object
    		StringTokenizer st= new StringTokenizer(originalStr, " ");
    
    		// reverse words
    		// by iterating through StringTokenizer tokens
    		for(int token = st.countTokens()-1; token >=0 ; token--) {
    
    			reversedStr = st.nextToken() + " " + reversedStr;
    		}
    
    		// print to console
    		System.out.println("Reverse String"
    				+ " using StringToknizer and for-loop:n");
    		System.out.println("Original String : "
    				+ originalStr);
    		System.out.println("Reversed String : "
    				+ reversedStr.trim());
    	}
    }
    

    Output:

    Reverse String using StringToknizer & for-loop:
    
    Original String : USA RSA KSA IND UK GER RUS
    Reversed String : RUS GER UK IND KSA RSA USA
    

    Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

    Related Articles:

    • String comparison – 3 ways
    • String concatenation – 2 ways
    • Reverse a String contents – 4 ways
    • Split a String contents – 3 ways
    • Overriding toString() method to print values of ArrayList in Java
    • How to left pad with zeroes to a String in Java

    References:

    • https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
    • https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
    • https://docs.oracle.com/javase/tutorial/java/data/strings.html
    • https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
    • https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
    • https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
    • https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

    Happy Coding !!
    Happy Learning !!

    Понравилась статья? Поделить с друзьями:
  • Reversing a sentence word by word
  • Reversed letters in word
  • Reverse words in word for printing
  • Reverse word order in string
  • Reverse word order in english