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;
}
}
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
-
Tokenize each word using
String.split()
method and create an array of words. -
Loop through words and join them in reverse order.
Java Implementation
this is sample
sample is this
Another approach using collections
We can use collections to reverse the order of words using the below steps:
-
Split the String into words using white space as separator
-
Reverse the collection consisting of words
-
Join the collections of the words back into a 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.
this is sample
siht si elpmas
Implementation
-
Tokenize each word using
String.split()
method and create an array of words. -
Loop through the string array and use
StringBuilder.reverse()
method to reverse each word. -
Join all reversed words to create the resulting 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:
- Reverse position of words in a string using recursion
- Reverse a string using recursion in Java
- Get distinct words from a given file in Java
- Create anagram buckets from a given input array of words
- Java Coding Problems for SDET Automation Engineer
- Anagrams string checker in Java
- 50 Java Interview Questions for SDET Automation Engineer