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

Carvia Tech | May 24, 2019 | 1 min read | 8 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 string
public void 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);
}
Input:
this is sample
Output
sample is this

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 string
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. Write a program to reverse a string using recursion in Java
  3. Java program to check if two strings are anagrams
  4. Create anagram buckets from a given input array of words
  5. Find longest non-repeating substring from a given string in Java
  6. How to reverse a number in Java
  7. Check whether given number is even or odd



Find more on this topic:
SDET Interviews image
SDET Interviews

End to end automation testing using Selenium Web Driver, Rest Assured, JMeter, Junit, TestNG etc.

Last updated 1 month ago


Recommended books for interview preparation:

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