Reverse order of words inside string in Java

Upasana | November 21, 2020 | 1 min read | 225 views


In this article, we will reverse the order of words in a given String using Java.

input

This is sample

output

sample is This

Solution

  1. Tokenize each word using String.split() method and create an array of words.

  2. Loop through words and join them in reverse order.

Java Implementation

Reverse the order of words in a string
class Util {
    public String reverseOrderOfWords(String input) {
        String[] words = input.split(" ");
        StringBuilder reverseString = new StringBuilder();

        for (int i = words.length - 1; i >= 0; i--) {
            reverseString.append(words[i]).append(" ");
        }
        System.out.println("reverseOrderOfWordsString = " + reverseString);
        return reverseString;
    }
}
Input:
this is sample
Output
sample is this

Another approach using collections

We can use collections to reverse the order of words using the below steps:

  1. Split the String into words using white space as separator

  2. Reverse the collection consisting of words

  3. Join the collections of the words back into a string

Java 8 Program to reverse the order of words in String
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseWords {

    public String reverseJava8Style(String input){
        List<String> list = Arrays.asList(input.split("[\\s]"));
        Collections.reverse(list);
        return String.join(" ", list);
    }
}

public class ReverseWordsTest {
    ReverseWords utils = new ReverseWords();

    @Test
    public void reverseJava8Style() {
        String reverseJava8Style = utils.reverseJava8Style("My Name is Tanishq");
        assertThat(reverseJava8Style, equalTo("Tanishq is Name My"));
    }
}

Reverse the words in String

A similar exercise could be to reverse the words themselves within a given string input.

Input
this is sample
Output
siht si elpmas

Implementation

  1. Tokenize each word using String.split() method and create an array of words.

  2. Loop through the string array and use StringBuilder.reverse() method to reverse each word.

  3. Join all reversed words to create the resulting string.

Reverse the words in a string
public class Util {
    public void reverseWordsInString(String input) {
        String[] words = input.split(" ");
        StringBuilder reverseString = new StringBuilder();
        for (String word : words) {
            String reverseWord = new StringBuilder(word).reverse().toString();
            reverseString.append(reverseWord).append(" ");
        }
        System.out.println("reverseWordsString = " + reverseString);
    }
}

Top articles in this category:
  1. Reverse position of words in a string using recursion
  2. Reverse a string using recursion in Java
  3. Get distinct words from a given file in Java
  4. Create anagram buckets from a given input array of words
  5. Java Coding Problems for SDET Automation Engineer
  6. Anagrams string checker in Java
  7. 50 Java Interview Questions for SDET Automation Engineer

Recommended books for interview preparation:

Find more on this topic: