Write a program to reverse the order of words in a string

Carvia Tech | August 03, 2019 | 1 min read | 70 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. Top 50 SDET Java Programming Interview Questions & Answers
  2. SDET: JUnit interview questions for automation engineer
  3. SDET: Rest Assured Interview Questions
  4. Write a program to reverse a string using recursion in Java
  5. Java program to check if two strings are anagrams
  6. Create anagram buckets from a given input array of words
  7. Check if the given string is palindrome



Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info